代码引发从一个未同步的代码块中调用对象同步方法

问题描述 投票:0回答:1

我正在编写非常简单的同步代码,但我确实陷入了这个错误中。什么可能导致错误?

程序在PulseAll(processingText)的最后一行抛出错误

更新:我的监视类中还有其他函数,该函数由主线程ProcessingText()调用,是否可能导致问题?

public void doWork(int threadTaskNumber)
        {
            while (!(bool)WorkDone)
            {
                lock (processingText)
                {
                    while (vowelCounter != 3 && threadTaskNumber != 0)
                    {
                        Monitor.Wait(processingText);
                    }

                    if (!(bool)workDone)
                    {

                        switch (threadTaskNumber)
                        {

                            case 0:
                                processingText += 'A';

                                if (vowelCounter != 3)
                                    vowelCounter++;
                                break;
                            case 1:
                                processingText += 'B';
                                break;
                            case 2:
                                processingText += 'C';
                                break;
                        }

                        if (++threadCounter == 15)
                            WorkDone = true;
                    }

                    Monitor.PulseAll(processingText);
                }
            }
        }

public void ProcessingText()
        {
            lock (processingText)
            {
                Console.WriteLine(processingText);
            }
        }
c# multithreading
1个回答
0
投票

SynchronizationLockException被抛出是因为这两行之间:

SynchronizationLockException

...变量Monitor.Wait(processingText); //... Monitor.PulseAll(processingText); 的值已更改。因此,processingText尝试使用当前线程不拥有的锁来发送脉冲,因此会观察到异常。

© www.soinside.com 2019 - 2024. All rights reserved.