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
DocuTerminal
How Long For Me
My Music To Me
SaveMySerials
TypeCount

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

Comparing XML files in C# Using Microsoft's Diff and Patch Tool

Reading a Microsoft Project file (mpp) in C#
Impersonating a user in ASP.NET
SharePoint RPC: Corrupted Binary Files

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. DocuTerminal - Online Filing Cabinet solution. Scan, search and archive your paper documents. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers My Music To Me - Stream your subsonic music collection to your Sonos wireless system TypeCount - Count how often you type across different computers! ServrTrackr - Monitor your SSL certificates, website uptime, and DNS configurations