Mar*_*ari 5 c# multithreading deadlock task taskcompletionsource
我在一段代码中遇到了僵局问题.值得庆幸的是,我已经能够在下面的例子中重现这个问题.作为普通的.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");
}
}
Run Code Online (Sandbox Code Playgroud)
我期望的完整序列如下:
Press any key...
entering worker
entering loop
entering stop
exiting worker
exiting stop
Run Code Online (Sandbox Code Playgroud)
但是,实际的序列在Thread.Join通话中停止:
Press any key...
entering worker
entering stop
Run Code Online (Sandbox Code Playgroud)
最后,如果我在MainAsync身体中插入一个小延迟,一切都很顺利.为什么(哪里)发生死锁?
注意:在原始代码中,我使用a SemaphoreSlim而不是a 来解决TaskCompletionSource,并且根本没有问题.我只想了解问题所在.