Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the Dispatcher in C#

Tags:

c#

I'm watching a video on asynchronous C# 5, and in the example he has an asynchronous method and a lambda callback function. Because the lambda callback function executes on a separate thread, trying to alter the UI within it causes an exception.

To mitigate this, he uses Dispatcher.RunAsync(...)

However I am confused about this. I made a new .NET 4.5 project and tried to find the Dispatcher class, but I can't find it anywhere. Google told me it was in the System.Windows.Threading namespace but I don't have this dll on my computer, only System.Windows

I also don't quite get how it works - looking at the MSDN documentation I can't really see how the Dispatcher (which presumably deals with all threads) will do stuff on the UI thread - the RunAsync method doesn't specify the thread that operations execute on.

I considered that maybe the dispatcher just runs things on the thread that was used to create the dispatcher, but since I can't try this out locally due to the above issue, I am at a loss.

Can anyone direct me to the solution?

like image 529
NibblyPig Avatar asked Jan 25 '26 04:01

NibblyPig


1 Answers

The video you have mentioned is about developing Windows Store app with the Windows Runtime and .NET Framework 4.5 and he uses the RunAsync method of the CoreDispatcher and that is part of the new Windows API and is in namespace Windows.UI.Core.

Stop as 00:20:21 and take a look at IntelliSense

like image 191
Jehof Avatar answered Jan 26 '26 17:01

Jehof