C#中的等待和脉冲异常

时间:2014-11-19 13:17:06

标签: c# monitor parallels

我有模拟时间。在每个步骤中我有4个主要功能f1,f2,f3,f4。 f1必须在所有之前运行,而f2,f3可以在f1并行之后运行。当f2和f3结束时可以启动f4。 我想创建4个任务来完成这些任务。但我不想在每一步都创建任务。(因为它有开销) 我想做完一项任务后,等待下一步。 我写这段代码但是给出了异常。

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

我在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 个答案:

答案 0 :(得分:0)

这不是你想要实现的目标:

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