Home
Blog
Contact
Mailing List
Software
Blog
Twitter
|
<< Back To All Blogs
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 your delegate function
private delegate void StatusMessageDelegate(object item);
// 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?
Tags
CSharp
Related Blogs
Creating a PDF with C# and iTextSharp
Creating an MD5 String Extension method in C#
Resizing Images in C#
Fixing "Error in loading DLL" in SharePoint
Enumerating a user secure certificate store in C#
Comments
Currently no comments.
Add A Comment
Name:
URL:
Email Address: (not public, used to send notifications on further comments)
Comments:

Enter the text above, except for the 1st and last character:
|