private static object lock_obj { get; set; } = new object();
/// <summary>
/// 线程死锁 、超时正确的处理姿势
/// </summary>
public Task DoSomething()
{
return Task.Run(() =>
{
bool token = false;
try
{
//尝试获取对象控制权
Monitor.TryEnter(lock_obj, 60 * 1000, ref token);
if (!token)
{
throw new AggregateException("获取线程控制超时");
}
//
//正式逻辑
//
}
catch (Exception ex)
{
// 写日志 ex.Message
Console.WriteLine(ex.Message);
}
finally
{
if (token)
{
Monitor.Exit(lock_obj);
}
}
});
}