Cancel C# 4.5 TcpClient ReadAsync by timeout

前端 未结 4 507
北海茫月
北海茫月 2021-01-11 23:32

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

4条回答
  •  生来不讨喜
    2021-01-12 00:02

    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

提交回复
热议问题