NerdyHearn
Home
Blog

Contact
Mailing List

Software

Active Directory Products
Object Compare
Permission Compare

IPhone Products
Calls To Calendar
SMS To CSV
SMS To Gmail
Voicemail To Gmail

Sites
How Long For Me
SaveMySerials

Blog
Twitter

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

Autostarting a Windows Service directly after install in C#
ConnectionString Switcharoo
Creating an Organizational Chart using C#: Part 2
Reading Digital Signatures from InfoPath Forms in MOSS 2007 and WSS 3.0 Workflow
A quick way to find C++ method signatures for C# Interop

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:


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