StreamSocket.InputStreamOptions.ReadAsync hangs when using Wait()

我只是一个虾纸丫 提交于 2020-01-04 06:31:06

问题


This is the smallest possible scenario, I was able to prepare:

  • This code connects to imap.gmail.com
  • Reads the initial server greeting (using Read method)
  • Sends NOOP command (NO Operation)
  • Reads NOOP command response (again using Read method)

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
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/16436824/streamsocket-inputstreamoptions-readasync-hangs-when-using-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!