Search code examples
c#concurrencymutexnonblockingthread-synchronization

Concurrency among C# threads


The scenario is the following one:

public class MainClass
{
    private static Object common_object;
    
    protected int Method_A()
    {
        //...
        lock (common_object)
        {
            // Works with common_object;
            //...
        }
        //...
        // Invokes another's thread Method_B
    }
    
    protected int Method_B()
    {
        //...
    }
}

I have a class: MainClass, and 2 (or more) instances of it.

The class has an object (private, static) which is shared by every instance and protected using lock(){...} where needed. I have no problems with it.

The class has also 2 methods which are the ones are making me going crazy trying to make everything work.

Let's say there is the "main method/function", A, which is invoked from the outside (I have no control over this invocations, nor knowledge of when is going to occur, but it's almost all the time with really short spaces between one invokation and the next one) on both threads.

There's also a second method, B, much shorter (both in time of execution and in code).

Here is the problem:

t2 invokes method A

t1 invokes method A

t2 (from method A) invokes t1's method B

t1 and t2 are blocked.

The method B of one thread(t2) is invoked from the method A of the other thread(t1), and if it is done when t2 is executing method A, everything crashes in one way or another. Usually both of the threads get blocked.

I'm using a flag-variable, so when t2 begins to execute method A, this flag is used by t1 to know he can't invoke t2's method B until t2 finishes the method A execution, but it seems I'm missing something because it doesn't work.

I'm used to work with Java, and thoung I guess there's the exactly same logic behind C# code, I think that there must be some functions or "tricks" in c# I am missing.

I guess (and hope) that there must be an easy way to solve this problem, since it's not a mayor one, and so I am finally here, asking for help after 3 days with no significative advances on my own.


Solution

  • Well, as terrybozzio suggested, it was about placing the eventwaithandles methods (wait, pulse) in the wrong place. Problem solved.

    Thanks for the tip.