wait and pulse Exception in C#

784 views Asked by At

I have simulation druring time. in every steps I have 4 main function f1,f2,f3,f4. f1 must be run before all and f2 , f3 can run after f1 parallel. when f2 and f3 is finished can start f4. I want create 4 task to do these. but I don't want create task in every step.(because it has overhead) I want after do one task , wait for next step. I write this code but give exception.

Task taskf1, taskf2, taskf3, taskf4;
    bool lockf1,lockf2, lockf3, lockf4_1,lockf4_2;
    Random r;
    public void f()
    {
        r = new Random();
        taskf1 = Task.Factory.StartNew(f1);
        taskf2 = Task.Factory.StartNew(f2);
        taskf3 = Task.Factory.StartNew(f3);
        taskf4 = Task.Factory.StartNew(f4);
        Monitor.Pulse(lockf1);

    }
    private void f1()
    {
        while (true)
        {
            Monitor.Wait(lockf1);
            Console.WriteLine("task 1");
            Thread.Sleep((int)(r.NextDouble() * 1000.0));
            Monitor.Pulse(lockf2);
            Monitor.Pulse(lockf3);
        }
    }
    private void f2()
    {
        while (true)
        {
            Monitor.Wait(lockf2);
            Console.WriteLine("task 2");
            Thread.Sleep((int)(r.NextDouble() * 1000.0));
            Monitor.Pulse(lockf4_1);
        }
    }
    private void f3()
    {
        while (true)
        {
            Monitor.Wait(lockf3);
            Console.WriteLine("task 3");
            Thread.Sleep((int)(r.NextDouble() * 1000.0));
            Monitor.Pulse(lockf4_2);
        }
    }
    private void f4()
    {
        while (true)
        {
            Monitor.Wait(lockf4_1);
            Monitor.Wait(lockf4_2);
            Console.WriteLine("task 4");
            Thread.Sleep((int)(r.NextDouble() * 1000.0));
            Monitor.Pulse(lockf1);
        }
    }

I give exception in one of Monitor.Wait(lockfn)

System.Threading.SynchronizationLockException was unhandled by user code
HResult=-2146233064
Message=Object synchronization method was called from an unsynchronized block of code.
Source=mscorlib
StackTrace:
   at System.Threading.Monitor.ObjWait(Boolean exitContext, Int32 millisecondsTimeout, Object obj)
   at System.Threading.Monitor.Wait(Object obj, Int32 millisecondsTimeout, Boolean exitContext)
   at System.Threading.Monitor.Wait(Object obj)
   at parallel_Test.Program.f1() in c:\Users\Sharafi\Documents\Visual Studio 2013\Projects\parallel Test\parallel Test\Program.cs:line 191
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
InnerException: 
1

There are 1 answers

4
galenus On

Isn't it what you are trying to achieve:

var firstTask = new Task(f1);
var secondTask = firstTask.ContinueWith(ignored => f2());
var thirdTask  = firstTask.ContinueWith(ignored => f3());
var fourthTask = Task.WhenAll(secondTask, thirdTask).ContinueWith(ignored => f4());

firstTask.Start();