为什么Console.WriteLine()在Stream.ReadAsync()的回调中阻塞?

Ton*_*ark 9 c# io console

我有一个回调函数,我在其中尝试写入我在重写的ReadAsync()中读取的数据.

private void StreamCallback(byte[] bytes)
{
    Console.WriteLine("--> " + Encoding.UTF8.GetString(bytes)); // the whole application is blocked here, why?
    if (OnDataReceived != null)
    {
        string data = Encoding.UTF8.GetString(bytes);
        OnDataReceived(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

重写的ReadAsync()如下所示.

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken)
{
    var read = await _originalStream.ReadAsync(buffer, offset, count, cancellationToken);
    _readCallback(buffer);

     return read;
}
Run Code Online (Sandbox Code Playgroud)

我实际想要实现的是在XmlReader解析之前监视网络流.这与我的另一个问题有关> 同时从同一个SslStream中读取?<.我该怎么办?

更新:

它实际上Encoding.UTF8.GetString(bytes)是阻止应用程序.为了使问题更加完整,我列出了用于读取XML流的代码.

using (XmlReader r = XmlReader.Create(sslStream, new XmlReaderSettings() { Async = true }))                
{
    while (await r.ReadAsync())
    {
        switch (r.NodeType)
        {
            case XmlNodeType.XmlDeclaration:
                ...
                break;
            case XmlNodeType.Element:
...
Run Code Online (Sandbox Code Playgroud)

ihe*_*nyi 1

根据您发布的代码, StreamCallback() 将阻塞,直到该流结束。您将字节指针传递给 Encoding.UTF8.GetString(bytes); 因此,它需要继续查询字节,直到到达末尾。它永远不会到达末尾,因为字节来自流,直到该流关闭为止。

您需要一次处理流一定数量的字节,或者直到看到某个字符。