Good Ol Cross-Threaded Socket Action

Tuesday, October 10th, 2006

So I have been working on a project lately using a lot of threading, and hence, a lot of cross-threading operations are required, especially for message passing and logging necessities. The security features in .NET 2.0 will no longer allow you to pass objects between threads unsafely without throwing an exception, but 1.1 would (of course I, being the programmer I am, would never dream of doing such a thing, hint hint, nudge nudge). So, to resolve this problem, after doing some serious and pretty in-depth research into getting around the issue, basically the only way to do it without creating static objects, which is just stupid, is by using delegation. Ill stop blabbing, here is the code I used to pass a simple string message between threads and record them in a listbox:

// Declare the method you will be calling, which encapsulates the item you wish to pass to
private void PrintStatusMessage(object item){
if (this.lstLog.InvokeRequired) {
this.lstLog.Invoke(new StatusMessageDelegate(this.PrintStatusMessage), item.ToString());
}
else
{
this.lstLog.Items.Add(item.ToString());
}
}

Then, regardless of which thread you are in, you just call PrintStatusMessage("This is my message"), and .NET will handle the rest because it has the nifty little InvokeRequired member. Pretty sweet hey?