这是我能准备的最小的场景:
- 此代码连接到imap.gmail.com
- 读取初始服务器问候语(使用Read方法)
- 发送NOOP命令(NO Operation)
- 读取NOOP命令响应(同样使用Read方法)
问题是第二个Read挂起。如果使用'await ReadAsync',它可以完美地工作。
当我中断程序时,我可以看到调用堆栈从task.Wait()开始,在System.Threading.Monitor.Wait()结束。
如果我一步一步调试,它不会挂起。我必须承认这看起来像是。net框架的错误,但也许我遗漏了一些明显的东西。
private static async Task<byte[]> ReadAsync(StreamSocket socket)
{
// all responses are smaller that 1024
IBuffer buffer = new byte[1024].AsBuffer();
await socket.InputStream.ReadAsync(
buffer, buffer.Capacity, InputStreamOptions.Partial);
return buffer.ToArray();
}
private static byte[] Read(StreamSocket socket)
{
Task<byte[]> task = ReadAsync(socket);
task.Wait();
return task.Result;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
Encoding encoding = Encoding.GetEncoding("Windows-1250");
using (StreamSocket socket = new StreamSocket())
{
await socket.ConnectAsync(
new HostName("imap.gmail.com"), "993", SocketProtectionLevel.Ssl);
// notice we are using Wait() version here without any problems:
byte[] serverGreetings = Read(socket);
await socket.OutputStream.WriteAsync(
encoding.GetBytes("A0001 NOOPrn").AsBuffer());
await socket.OutputStream.FlushAsync();
//byte[] noopResponse = await ReadAsync(socket); // works
byte[] noopResponse = Read(socket); // hangs
}
}
我在最近的MSDN文章和我的博客中解释了这个死锁的原因。
简短的回答是,你不应该调用Wait
或Result
在async
代码;你应该一直使用await