[英]Exception : Object synchronization method was called from an unsynchronized block of code
[英]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.