Synchronization in WinForms with Lambdas
In a recent thread in the ADVANCED-DOTNET mailing list, the topic of multiple threads and WinForms came up. As you probably know, Windows Forms controls can only be accessed/manipulated from the thread on which they were created. The topic of Control.Invoke came up and Richard Blewett made the following comment:
As an aside, I generally find the programming model introduced with SynchronizationContext in v2.0 to be simpler than using the Control.InvokeRequired/Control.BeginInvoke pair
I had never even heard of this object so I did some research. There's a WindowsFormsSynchronizationContext that handles executing code on the main UI thread. Matt Dotson has an example of using the synchronization context to update a Textbox from a background thread. The code is pretty simple:
1: context.Send(new SendOrPostCallback(
2: delegate(object state)
3: {
4: //This executes on the ui thread
5: textBox1.Text = DateTime.Now.ToLongTimeString();
6: }
7: ), null);
But it becomes even simpler with C# 3.5's lambda syntax:
1: context.Send(s => textBox1.Text = DateTime.Now.ToLongTimeString(), null);
Nice!