You don't have to run async methods using Task.Run()
, or any other special means, just call them. And in your case, that's exactly what is causing the problem.
Given function like this:
Action f = async () =>
{
while (true)
{
// modify the observable collection here
await Task.Delay(500);
}
};
Calling it like this from some method run on the UI thread, like an event handler:
f();
works exactly as it should. It executes the first iteration of the cycle and then returns. The next iteration is executed after 500 ms (or more, if the UI thread is busy) on the UI thread.
On the other hand, if you call it like this:
Task.Run(addNames);
it doesn't work correctly. The reason for this is that async
methods try to continue in the same context as they were started (unless you explicitly specify otherwise). The first version was started on the UI thread, so it continued on the UI thread. The second version started on a ThreadPool thread (thanks to Task.Run()
) and continued there too. Which is why it caused your error.
All this is done using SynchronizationContext
, if one is present.