等待并脉冲 C# 中的异常

本文关键字:异常 脉冲 等待 | 更新日期: 2023-09-27 18:30:56

我有模拟时间。 在每个步骤中,我都有 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);
        }
    }

我在其中一个监视器中给出例外.等待(锁定)

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: 

等待并脉冲 C# 中的异常

这不是你想要实现的吗:

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