Home > .NET Development > Windows Forms Cross Threading Simple Solution

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: