英文:
Code still waiting until loop ends despite using await Task.Run()
问题
以下是翻译好的部分:
我有一段代码,我想在后台使用Task.Run()运行一个循环,并使用Invoke()更新循环中的一些UI元素。然而,即使使用了await Task.Run(),代码仍然会等待循环结束才继续执行下一行代码。
这是相关的代码片段:
await Task.Run(() =>
{
while (panel1.Controls.Contains(button))
{
button.Invoke((MethodInvoker)(() =>
{
// 在这里进行UI更新逻辑
}));
Thread.Sleep(1);
}
});
我期望使用await Task.Run(),循环会在后台异步运行,允许代码继续执行。然而,看起来代码仍然在等待循环结束之后才继续前进。
我是否漏掉了什么?如何确保代码在不等待循环结束的情况下继续执行?任何帮助将不胜感激。谢谢!
英文:
I have a piece of code where I want to run a loop in the background using Task.Run() and update some UI elements within the loop using Invoke(). However, even after using await Task.Run(), the code still waits until the loop ends before proceeding to the next line of code.
Here's the relevant code snippet:
await Task.Run(() =>
{
while (panel1.Controls.Contains(button))
{
button.Invoke((MethodInvoker)(() =>
{
// UI update logic here
}));
Thread.Sleep(1);
}
});
I expected that by using await Task.Run(), the loop would run asynchronously in the background, allowing the code to continue executing. However, it seems that the code still waits for the loop to finish before moving forward.
Am I missing something here? How can I ensure that the code continues executing without waiting for the loop to end? Any help would be appreciated. Thank you!
答案1
得分: 1
没有严重的问题。当你在等待之前使用 await
来调用可等待的方法(例如 Task.Run
),它会等待直到任务完成。
绝对可以防止你的 UI
线程被阻塞。以前在没有 async/await
的情况下,在 WinForm
、WPF
等等中存在一个旧问题。
所以,如果你想在后台运行这个任务,你应该像这样做:
var BackgroundTask = Task.Run(() =>
{
while (panel1.Controls.Contains(button))
{
button.Invoke((MethodInvoker)(() =>
{
// 在这里进行UI更新逻辑
}));
Thread.Sleep(1);
}
});
现在你可以在任何时候停止这个任务,而且不会像以前一样阻塞你的 UI
线程。
英文:
There is no serious problem. When you put await
before an awaitable call (e.g. Task.Run
) It waits for it to the end.
Definitely what you did prevents your UI
thread from blocking. There was an old issue when we had no async/await
on WinForm, WPF, ...
.
So if you want to run this task on background you should do something like this:
var BackgroundTask = Task.Run(() =>
{
while (panel1.Controls.Contains(button))
{
button.Invoke((MethodInvoker)(() =>
{
// UI update logic here
}));
Thread.Sleep(1);
}
});
Now you are able to stop this task whenever you wanted and It won't block your UI
thread as before.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论