StreamSocket.InputStreamOptions.ReadAsync 在使用 Wait() 时挂起 [英] StreamSocket.InputStreamOptions.ReadAsync hangs when using Wait()

查看:25
本文介绍了StreamSocket.InputStreamOptions.ReadAsync 在使用 Wait() 时挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最小可能的场景,我能够准备:

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

  • 此代码连接到 imap.gmail.com
  • 读取初始服务器问候语(使用 Read 方法)
  • 发送 NOOP 命令(无操作)
  • 读取 NOOP 命令响应(再次使用 Read 方法)

问题在于第二次读取挂起.如果使用'await ReadAsync',它可以完美运行.

The problem is that the second Read hangs. It works perfectly if 'await ReadAsync' is used.

当我中断程序时,我可以看到调用堆栈从 task.Wait() 开始并在 System.Threading.Monitor.Wait() 结束.

When I break the program I can see the Call Stack starts at task.Wait() and ends on System.Threading.Monitor.Wait().

如果我一步一步调试它,它不会挂起.我必须承认它看起来像一个 .NET 框架错误,但也许我遗漏了一些明显的东西.

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

推荐答案

我解释了这个僵局的原因 在我最近的 MSDN 文章 以及 在我的博客上.

I explain the cause of this deadlock in my recent MSDN article as well as on my blog.

简短的回答是,您不应该async代码上调用WaitResult;你应该一直使用 await.

The short answer is that you're not supposed to call Wait or Result on async code; you should use await all the way.

这篇关于StreamSocket.InputStreamOptions.ReadAsync 在使用 Wait() 时挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆