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