Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Console.WriteLine() block in callback from Stream.ReadAsync()?

Tags:

c#

io

console

I have a callback function in which I am trying to write the data that I read in an overriden 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);
    }
}

The overriden ReadAsync() looks as follows.

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

What I actually want to achieve is to monitor a network stream just before it gets parsed by an XmlReader. This relates to my other question > Reading from same SslStream simultaneously? <. How would I do that?

UPDATE:

It is actually Encoding.UTF8.GetString(bytes) that is blocking the application. In order for the question to be more complete I am listing the code for reading the XML stream.

using (XmlReader r = XmlReader.Create(sslStream, new XmlReaderSettings() { Async = true }))                
{
    while (await r.ReadAsync())
    {
        switch (r.NodeType)
        {
            case XmlNodeType.XmlDeclaration:
                ...
                break;
            case XmlNodeType.Element:
...
like image 787
Tony Stark Avatar asked Aug 23 '13 15:08

Tony Stark


1 Answers

Based on the code you posted, StreamCallback() will block until that stream ends. You pass a byte pointer to Encoding.UTF8.GetString(bytes); So, it needs to keep querying bytes until it reaches the end. It will never reach the end since bytes comes from a stream until that stream is closed.

You need to either process your stream a certain number of bytes at a time or until a certain character is seen.

like image 103
iheanyi Avatar answered Oct 21 '22 20:10

iheanyi