Mailing List



NerdyHearn - Blog

<< 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());

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?



Related Blogs

Calling .NET WebService From PHP
Creating a PDF with C# and iTextSharp
Determining if a computer is a laptop or desktop in C#
Creating a reusable web client for PUT, POST, and DELETE in C#
Validate a Windows Username and Password against Active Directory


Currently no comments.

Add A Comment



Email Address: (not public, used to send notifications on further comments)


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

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers