避免lock(this)容易发生死锁
避免lock(this)
lock(this)容易发生死锁
应该对私有引用变量加锁
下面是发生死锁示例
program.cs
// See https://aka.ms/new-console-template for more information
using DeadLock;
Console.WriteLine("Hello, World!");
SynchroThis st = new SynchroThis();
Monitor.Enter(st);
// 对象本身已经被锁 ,所以Work中lock一直无法等待到锁释放,发生死锁
//Monitor.Exit(st);提前释放锁
Thread t = new Thread(st.Work);
t.Start();
t.Join();
//程序不会执行到这里
Console.WriteLine("程序结束");
internal class SynchroThis
{
private int i = 0;
/// <summary>
/// lock(this)不够健壮
/// </summary>
/// <param name="state"></param>
public void Work(Object state)
{
lock (this)
{
Console.WriteLine($@"i的值为{i.ToString()}");
i++;
Thread.Sleep(200);
Console.WriteLine($@"i自增,i的值为{i.ToString()}");
}
}
}
Examples
https://github.com/huzuohuyou/DotNet6-Examples/tree/main/DeadLock