Archive for July, 2009

Windows Forms Cross Threading Simple Solution

I found this article in the CodeProject Newsletter that presents an extension method that takes a delegate to run on the UI.

And this was my comment.

I have came across the same issue before, I was developing a windows forms application client used by more than 30 developer in the same time and the application was taking a lot of time just to access the UI from another thread.

I got ANTS Profiler to get for me the line of code that takes that much time, and it was this

if (form.InvokeRequired)
form.Invoke(code); //this

I searched for a better solution and got this simple way with one line of code to access the UI.

SynchronizationContext syncContext;
syncContext = SynchronizationContext.Current; //in constrcutor
syncContext.Send(new SendOrPostCallback((s) => { this.myTextBox.Text = "some text"; }), null);

After running ANTS Profiler again I noticed a very big difference in the time spent to accomplish the same job!.

Categories: .NET Development