Cancel C# 4.5 TcpClient ReadAsync by timeout

miksh picture miksh · Mar 7, 2013 · Viewed 9.1k times · Source

What would the proper way to cancel TcpClient ReadAsync operation by timeout and catch this timeout event in .NET 4.5?

TcpClient.ReadTimeout seems to be applied to the sync Read only.

UPDATE:
Tried tro apply the approach desribed here Cancelling an Asynchronous Operation

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

but it never cancels by timeout. Is anything wrong?

Answer

Khalid Omar picture Khalid Omar · Dec 17, 2016

so I know that was from a long time but google still drive me here and I saw there is none marked as answer

for me, I solve like that I make an extension to add a method ReadAsync that takes extra 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;
}

so if it returned -1 that mean the read timed out