Avoiding Task.Run causing deadlock on Main thread (C#)

Viewed 160

I believe, while unlikely, that it is possible for a Task queued up using Task.Run() to end up running on the Main thread.

I'm concerned that (in my WPF app), If I am using App.Current.Dispatcher.Invoke(), or similar, inside this Task, I will cause a deadlock.

Is this a valid fear? If so, is there a way to prevent this from happening (without checking the current thread *isnt* the main thread).

Thanks

1 Answers

I believe, while unlikely, that it is possible for a Task queued up using Task.Run() to end up running on the Main thread.

You believe incorrectly: this is not possible. Task.Run dispatches to the ThreadPool, not the UI thread's dispatcher. The two are entirely separate.

I'm concerned that (in my WPF app), If I am using App.Current.Dispatcher.Invoke(), or similar, inside this Task, I will cause a deadlock.

You should avoid using Invoke anyway, because of the risk of deadlocks. The risk is that the UI thread is waiting for your thread to do something, and by synchronously waiting for the UI thread to be free enough to process your message, you're risking deadlock.

You can normally use BeginInvoke instead (having a background thread whose progress depends on what the UI is doing is normally bad design), but you rarely need this when you're using await and Progress<T>/IProgress<T>.

Related