Friday, November 6, 2015

C# Background Workers Using Shared Memory

It doesn't happen often in my particular coding shop, but once in a rare while the requirement for different threads in a program to use a shared memory variable rears it's head.  It really isn't difficult to handle this requirement in C#; actually, it is surprisingly easy if you are careful to avoid deadlock situations,

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

The first line locks MsgLock, or causes the thread to wait until another thread's lock is released.  The ReportProgress() line is a method belonging to a BackgroundWorker, that line, in this case is accessing our shared variable Messages.  The last line in the Lock() block assigns something to the shared variable.

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.