views:

39

answers:

1

I was wondering how I would use the Dispatcher in WPF to safely update my BindingList collection from another thread?

I am also open for other solutions,

Many Thanks, Kave

A: 

I prefer scheduling a Task to the UI thread. You can get the UI thread scheduler by calling TaskScheduler.FromCurrentSynchronizationContext while on the UI thread. MSDN has an example here.

I generally prefer SynchronizationContext-based solutions instead of Dispatcher-based solutions because they are not tied to WPF/Silverlight. So, it's possible to write a common business object layer that handles the synchronization yet can be used from WPF, ASP.NET, Windows Forms, Win32 Services, etc.

Stephen Cleary
Thanks for your answer. I managed to study the different ways of multithreading by applying Dispatcher, SynchronizationContext and Tasks. Its very interesting indeed.I am a bit surprised that SynchronizationContext exists since .NET 2.0 and I didn't know about it. I always used the classic control.Invoke in this mater. Double surprising since I did the MCPD certificate of Microsoft and they dont teach that in their materials at all. The TaskScheduler for Thread synchronization is only available in .NET 4.0 is that correct? This could also be done alternatively with manualresetevent, right?
Kave
Sadly, the .NET 1-era MSDN docs recommending `Control.Invoke` are still carried forward into .NET 4.0, so most people aren't aware of the superior `SynchronizationContext`. `TaskScheduler` has been backported to .NET 3.5 as part of the [Rx library](http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx). And, no, `ManualResetEvent` is used for *synchronization*, whereas `SynchronizationContext` (in spite of the name) is actually used for *scheduling* work to other contexts. You can't use `ManualResetEvent` to run a delegate on the UI thread.
Stephen Cleary
BTW, I've written quite a bit about `SynchronizationContext` on [my blog](http://nitoprograms.com/), under the [Threading tag](http://nitoprograms.blogspot.com/search/label/Threading).
Stephen Cleary