public static void Init()
{
//var task = GetSource1();
//var task = GetSource2();
//var task = GetSource3();
var task = MyClient();
MessageBox.Show(task.Result);
}
private static async Task<string> GetSource1()
{
var sourceTask = WebClient();
sourceTask.ConfigureAwait(false);
return await sourceTask;
}
private static async Task<string> GetSource2()
{
var sourceTask = MyClient();
sourceTask.ConfigureAwait(true);
return await sourceTask;
}
private static async Task<string> GetSource3()
{
var sourceTask = MyClient();
sourceTask.ConfigureAwait(false);
return await sourceTask;
}
private static async Task<string> WebClient()
{
return await new WebClient().DownloadStringTaskAsync("http://4pda.ru").ConfigureAwait(false);
}
private static Task<string> MyClient()
{
var t = new Task<string>(() => new WebClient().DownloadString("http://4pda.ru"));
t.ConfigureAwait(false);
t.Start();
return t;
}
这段代码工作正常。我得到了源代码MessageBox
。但是,为什么我在使用时会出现死锁var task = GetSource3()
?我认为它必须有效,因为我使用ConfigureAwait(false)
并避免了上下文切换