Posted by Anuraj on Friday, March 22, 2013
Long back I wrote a post about how to fix - System.InvalidOperationException â€“ Cross-thread operation not valid exception, while we try to access user interface elements from a different thread, other than the thread(normally main thread), which created the user interface elements. .NET 2.0 brings us SynchoronizationContext which allows us to execute a section of code in the UI context (the thread that created the UI). Also, it allows us to specify if the background thread will block waiting for the UI thread (using Send) or will not block (using Post). SynchoronizationContext class can be used in Windows Forms, WPF, and ASP.Net etc. For Windows forms, you can get the UI context from the WindowsFormsSynchronizationContext.Current property. For WPF, the implementation is DispatcherSynchronizationContext class.
In the following example, I am updating the UI from a separate thread, without the _synchronizationContext.Post() method, it will throw an InvalidOperationException. Here is the implementation.
When the value is assigned to textbox, if you look the threads window, you can find, it is running under main thread.
You can find more details about WindowsFormsSynchronizationContext class in MSDN