The key to this solution is a simple static class:
using System;
using System.Collections.Generic;
using System.Text;
namespace ThreadCom
{
static class StaticShare
{
public static object MsgLock = new object(); // Functions as a lock when accessing Messages.
public static string Messages = ""; // This is what is shared and used in all threads of this sample program.
}
}
Basically, this snippet of C# code creates a static class with two public properties: MsgLock and Messages. MsgLock is used to control access to Messages; a string that contains the data shared among the different threads. Remember, performance is important; keep the shared static variable terse and small.
Here is how a thread (specifically a BackgroundWorker) might use the StaticShare class to lock, access and change the shared data without causing noticeable contention or throwing exceptions:
lock (StaticShare.MsgLock)
{
ReportProgress(0, "From " + BWName + " -> " + StaticShare.Messages);
StaticShare.Messages = BWName + " current time: " + DateTime.Now.ToString();
}
One big caveat here... Make the code within the lock() block short, concise, to the point and fast. If the code there is time-consuming or performs poorly, the lock() could cause other threads to be blocked.
Remember... thread blocking is not cool!
You can download the entire c# project from my Google Drive here. Standard code disclaimer: This code is for education, information and perhaps a few laughs. It may not be perfect but does demonstrate a valid implementation of using shared storage with a multi-threaded C# application.
-whew-
No comments:
Post a Comment