Home > Software engineering >  A queued function (void) for multiple threads in C#
A queued function (void) for multiple threads in C#

Time:11-23

I have multiple threads in my C# program. Now they call a specific function once in a while during their runtime. Now I want to make sure that they never execute that specific function at the same time (since it leads to some anomalies in my program), one call to the function must finish before the next call starts. (much like a queue).

Is it possible to accomplish this? (Does not have to be a function).

Here's a diagram if some couldn't understand:

enter image description here

CodePudding user response:

You can use lock keyword to prevent execution of code fragment in parallel. Just wrap your function's calls into a lock statement or add a lock inside function itself.

class MyClass
{
    private object lockObj = new();
    
    public void MyFunction()
    {
        lock(lockObj)
        {
            //code goes here
        }
    }
}

    //usage
    void Test()
    {
        var myClass = new MyClass();
        var thread1 = new Thread(ThreadFunc);
        var thread2 = new Thread(ThreadFunc);
        
        thread1.Start(myClass);
        thread2.Start(myClass);
    }
    
    public static void ThreadFunc(object myClassObj)
    {
        var myClass = (MyClass)myClassObj;
        myClass.MyFunction();
    }

Note lockObj object here. To acheive behaviour you want, you should use exactly the same lockObj value in the lock statements. So, the following is WRONG

//WRONG, do NOT DO this
    var myClass1 = new MyClass();
    var myClass2 = new MyClass();
    var thread1 = new Thread(ThreadFunc);
    var thread2 = new Thread(ThreadFunc);

    thread1.Start(myClass1);
    thread2.Start(myClass2);

Here we have two independent instances of MyClass, so each instance has their own value of lockObj and thus this instances will not lock each other, so parallel exectution of myClass1.MyFunction() and myClass2.MyFunction() is allowed here.

  • Related