通过超时取消C#4.5 TcpClient ReadAsync [英] Cancel C# 4.5 TcpClient ReadAsync by timeout

查看:72
本文介绍了通过超时取消C#4.5 TcpClient ReadAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过超时取消TcpClient ReadAsync操作并在.NET 4.5中捕获此超时事件的正确方法是什么?

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

TcpClient.ReadTimeout似乎已应用于同步只读.

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

更新:
尝试使用此处描述的方法取消异步操作

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?

推荐答案

所以我知道那是很长一段时间了但是谷歌仍然把我带到这里我看到没有标记为答案

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

对我来说,我这样解决我进行了扩展以添加需要额外超时的方法ReadAsync

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

因此,如果返回-1,则表示读取超时

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

这篇关于通过超时取消C#4.5 TcpClient ReadAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆