繁体   English   中英

代码抛出 Object 同步方法是从未同步的代码块中调用的

[英]code throws Object synchronization method was called from an unsynchronized block of code

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

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

更新:在我的监控 class 中还有其他 function 由主线程 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);
            }
        }

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

Monitor.Wait(processingText);
//...
Monitor.PulseAll(processingText);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM