我要檢查一些鎖定行爲,我不明白這一點:鎖定在一個基本類型
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
MultithreadedMethod();
});
}
Thread.Sleep(2000);
Console.WriteLine(count);
}
static int count = 0;
private static readonly int sync = 5;
public static void MultithreadedMethod()
{
if (Monitor.TryEnter(sync))
{
count++;
Monitor.Exit(sync);
}
}
我認爲這不應該工作,由於我做的一個整數值同步。第一次拳擊,然後拆箱,我應該得到一個System.Threading.SynchronizationLockException,因爲缺少同步塊根(我知道這是特定於引用類型)。 我不會愚弄自己,即使這只是爲了迭代而工作,它並不是真正的同步..所以,考慮到增量操作的非原子屬性..我不會得到確定性的結果..我知道這個的。
事實上,當我擺脫那個Thead.Sleep,並把任務等待..異常到位。
Task.Factory.StartNew(() =>
{
MultithreadedMethod();
}).Wait();
我覺得異常應該在這裏拋出:Monitor.Exit(sync)
但什麼抓住了嗎?
更新1:圖片已添加。
當我運行上面的代碼時,它會從'Exit'引發異常。當然你從任務中捕獲異常? –
@PatrickHofman這就是我擁有的一切。剛拍了照片。 –