我的一段代码面临死锁问题。值得庆幸的是,我已经能够在下面的示例中重现该问题。作为普通的 .Net Core 2.0 控制台应用程序运行。
class Class2
{
static void Main(string[] args)
{
Task.Run(MainAsync);
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static async Task MainAsync()
{
await StartAsync();
//await Task.Delay(1); //a little delay makes it working
Stop();
}
static async Task StartAsync()
{
var tcs = new TaskCompletionSource<object>();
StartCore(tcs);
await tcs.Task;
}
static void StartCore(TaskCompletionSource<object> tcs)
{
_cts = new CancellationTokenSource();
_thread = new Thread(Worker);
_thread.Start(tcs);
}
static Thread _thread;
static CancellationTokenSource _cts;
static void Worker(object state)
{
Console.WriteLine("entering worker");
Thread.Sleep(100); //some work
var tcs = (TaskCompletionSource<object>)state;
tcs.SetResult(null);
Console.WriteLine("entering loop");
while (_cts.IsCancellationRequested == false)
{
Thread.Sleep(100); //some work
}
Console.WriteLine("exiting worker");
}
static void Stop()
{
Console.WriteLine("entering stop");
_cts.Cancel();
_thread.Join();
Console.WriteLine("exiting stop");
}
}
我期望的是完整的序列如下:
Press any key...
entering worker
entering loop
entering stop
exiting worker
exiting stop
Thread.Join
但是,实际序列在调用中停止:
Press any key...
entering worker
entering stop
最后,如果我在正文中插入一个小延迟MainAsync
,一切都会好起来的。为什么(在哪里)会发生死锁?
SemaphoreSlim
注意:在我使用 a而不是 a解决的原始代码中TaskCompletionSource
,根本没有问题。我只想了解问题出在哪里。