Wednesday, February 08, 2006

New in .NET 2.0 - SynchronizationContext

The class SynchronizationContext is a new addition to the 2.0 framework and fills a much needed void. Part of the problem with the 1.0 framework is that a tool/object/whatever that wanted to do work in the background or recieve background notifications had to be aware of the environment that it existed in.

The most popular example is the Windows Forms model. All properties and methods on any object in the System.Windows.Forms namespace can only be manipulated from the Thread that they were created on. So any tool that was used within a forms application had to take one of 2 routes
  1. Accept some form of synchronization object (like a generic Control) and use that to invoke operations onto the appropriate thread
  2. Generically throw up events and make the caller responsible for threading concerns

Both approaches have their drawbacks and advantages. SynchronizationContext fixes this issue. It lets the application model dictate how events and callbacks should behave with respect to threading.

The two main methods are Post(async) and Send(sync). Both accept a delegate and the application model specific SynchronizationContext will invoke the delegate in the proper thread. By default they are just invoked but this can be overridden. Your code can access the context through the static property "Current".

The windows form model injects it's own SynchronizationContext that will force the delegates to be run on the GUI thread. Now background working code can exist independentyl of it's environment. Environments simply need to setup their own context.

This is a lot like option #2 above except that it's an application wide solution rather than an object specific one.

0 Comments:

Post a Comment

<< Home