[英]Monitor and Object synchronization method was called from an unsynchronized block of code
[英]Error while using Monitor class in WinForms. Object synchronization method was called from an unsynchronized block of code
使用System.Threading的Win Form應用程序。 兩個線程threadA和threadB以相同的方法sumNumber啟動。 sumNumber更新變量total 。 因此這兩個線程嘗試更新相同的變量。
使用監視器類來同步對總變量的訪問。
在WindowsFormsApplication2.exe中獲得“ 類型為System.Threading.SynchronizationLockException的未處理異常 ” 的運行時異常
附加信息: 從未同步的代碼塊中調用了對象同步方法 。
我該如何正確使用Monitor類。
int total;
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
total = 0;
Thread threadA;
Thread threadB;
threadA = new Thread(sumNumber);
threadA.Start();
threadB = new Thread(sumNumber);
threadB.Start();
threadA.Join();
threadB.Join();
listBox1.Items.Add("Total is: " + total);
}
public void sumNumber()
{
long numRepeats = 100000;
for (int i = 0; i < numRepeats; i++)
{
Monitor.Enter(total);
total = total + 10;
Monitor.Exit(total);
}
}
傳遞給Monitor.Enter和Monitor.Exit的對象必須相同。 由於total的值發生了變化,Monitor.Exit嘗試退出,但沒有與相應對象對應的Monitor.Enter,因此拋出異常
你應該有
private readonly object TotalLock = new object();
作為成員變量,然后
Monitor.Enter(TotalLock);
total = total + 10;
Monitor.Exit(TotalLock);
可以縮短為
lock (TotalLock)
{
total = total + 10;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.