Reputation: 179
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!
Upvotes: 0
Views: 108
Reputation: 1479
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.
Upvotes: 1