This is the smallest possible scenario, I was able to prepare:
The problem is that the second Read hangs . It works perfectly if 'await ReadAsync' is used.
When I break the program I can see the Call Stack starts at task.Wait() and ends on System.Threading.Monitor.Wait().
If I debug this step by step, it does not hang. I must admit it looks like a .NET framework bug, but maybe I'm missing something obvious.
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 NOOP\r\n").AsBuffer());
await socket.OutputStream.FlushAsync();
//byte[] noopResponse = await ReadAsync(socket); // works
byte[] noopResponse = Read(socket); // hangs
}
}
I explain the cause of this deadlock in my recent MSDN article as well as on my blog .
The short answer is that you're not supposed to call Wait
or Result
on async
code; you should use await
all the way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.