Cancel C # 4.5 TcpClient ReadAsync by timeout

How could I cancel the TcpClient ReadAsync operation with a timeout and catch this timeout event in .NET 4.5?

TcpClient.ReadTimeout seems to apply only to synchronization. Only for reading.

UPDATE:
Try the approach described here. Cancel asynchronous operation

var buffer = new byte[4096];
CancellationTokenSource cts = new CancellationTokenSource(5000);
int amountRead = await tcpClientStream.ReadAsync(buffer, 0, 4096, cts.Token);

but it is not canceled by a timeout. Something is wrong?

+4
source share
3 answers

so I know that it has been a long time but google is still me here and I saw that there is no one marked as an answer

for me, I decide so I am doing an extension to add the ReadAsync method, which requires an additional timeout

        public static async Task<int> ReadAsync(this NetworkStream stream, byte[] buffer, int offset, int count, int TimeOut)
    {
        var ReciveCount = 0;
        var receiveTask = Task.Run(async () => { ReciveCount = await stream.ReadAsync(buffer, offset, count); });
        var isReceived = await Task.WhenAny(receiveTask, Task.Delay(TimeOut)) == receiveTask;
        if (!isReceived) return -1;
        return ReciveCount;
    }

, -1, ,

+12

: , . https://gist.github.com/svet93/fb96d8fd12bfc9f9f3a8f0267dfbaf68

:

, , , , :

public static class TcpStreamExtension
{
    public static async Task<int> ReadAsyncWithTimeout(this NetworkStream stream, byte[] buffer, int offset, int count)
    {
        if (stream.CanRead)
        {

            Task<int> readTask = stream.ReadAsync(buffer, offset, count);
            Task delayTask = Task.Delay(stream.ReadTimeout);
            Task task = await Task.WhenAny(readTask, delayTask);

            if (task == readTask)
                    return await readTask;

        }
        return 0;
    }
}

, , - , ( ), , Task.Run , .

:

, , . readAsync, -, , , , , , .

+3

You must implement it yourself: it is not available in this class.

you must use a timer that will kill the async operation after a period of time or use the sync version of synchronization in the background.

there you can find an example: Implementing a timeout using NetworkStream.BeginRead and NetworkStream.EndRead

0
source

Source: https://habr.com/ru/post/1543231/


All Articles