This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Friday, June 12, 2009

Crossing Thread Boundaries

Sometimes you find a solution to a problem and you just add it to your Swiss Army Knife of code to handle similar problems down the road.  If you’ve ever used a Timer on a WinForms application, you’ve likely run into the following error message:

Cross-thread operation not valid: Control 'someControl' accessed from a thread other than the thread it was created on.

Since .Net 2.0 I’ve run the same game strategy for hopping back over to the UI thread when I want to make updates.  Basically, I make a delegate with the appropriate parameters to handle whatever update I want (like strings for the Text property on a Lable), then check InvokeRequired to re-call the method, if necessary.

But I’ve been neglecting a good friend: anonymous delegates.

Today I came across an article related to something entirely different and they mentioned ‘MethodInvoker’.  This turns out to be a very clean implementation.  Because the anonymous delegate gets the scope variables of the method it’s created in, you don’t have to pass parameters, nor do you have to re-call the same method.

The end result – sans named delegate – looks elegantly like the following example:

void CoordsReceived(object sender, CoordinatesReceivedEventArgs e)
{
this.Invoke(new MethodInvoker(delegate()
{
lblLattitude.Text = e.Lattitude.ToString();
lblLongitude.Text = e.Longitude.ToString();
}));
}




Still very readable, arguably more so, and still takes care of getting back on the right thread to update the UI.



I can’t believe I missed this for so long…all those delegates!

No comments:

Post a Comment