C#在网络流上设置WriteTimeout / ReadTimeout没有区别?

问题描述 投票:0回答:1

我在我的Xamarin.Forms应用程序中有以下方法代码

using (TcpClient client = new TcpClient(ip, port))
using (NetworkStream stream = client.GetStream())
{
    byte[] messageBytes = PrepareMessageBytes();

    //
    // Setting these seam to have no effect
    //
    stream.WriteTimeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;
    stream.ReadTimeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;

    //
    // I have set read and write timeouts above but when 
    // hitting this line, app hangs indefinitely?  
    // I would expect that after 10 seconds, a IOException
    // will be thrown
    await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
    stream.Flush();

    byte[] buffer = new byte[1024];
    StringBuilder builder = new StringBuilder();
    int bytesRead = 0;

    while (stream.DataAvailable)
    {
        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
        builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
    }

    string msg = receivedMessage.ToString();
} 

在上面,我将写入和读取超时都设置为10秒。我知道我的代码挂断电话:

等待stream.WriteAsync(...)

,但我希望在10秒后,将抛出IOException。基于MS文档,异步写入/读取不是这种情况。

如何为WriteAsync / ReadAsync方法调用设置超时?

更新 - 基于斯蒂芬评论的第二次尝试

根据Stephen的评论,我更新了代码并将其包装到try..catch中以处理OperationCancelledException。但是现在这导致了比以前更多的问题,App仍然会在大部分时间内挂起:

try
{
    using (TcpClient client = new TcpClient(ip, port))
    using (NetworkStream stream = client.GetStream())
    using (var writeCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
    {
        byte[] messageBytes = PrepareMessageBytes();

        await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
        await stream.FlushAsync();

        byte[] buffer = new byte[1024];
        StringBuilder builder = new StringBuilder();
        int bytesRead = 0;

        while (stream.DataAvailable)
        {
            using (var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
            builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
        }

        string msg = receivedMessage.ToString();
    }
catch (OperationCancelledException ex)
{
    Debug.WriteLine(ex.Message);
}
c# timeout networkstream
1个回答
2
投票

如何为WriteAsync / ReadAsync方法调用设置超时?

您使用带有CancellationToken参数的重载:

using (TcpClient client = new TcpClient(ip, port))
using (NetworkStream stream = client.GetStream())
using (var writeCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
    byte[] messageBytes = PrepareMessageBytes();

    await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
    await stream.FlushAsync();

    byte[] buffer = new byte[1024];
    StringBuilder builder = new StringBuilder();
    int bytesRead = 0;

    while (stream.DataAvailable)
    {
        using (var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
            bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
        builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
    }

    string msg = receivedMessage.ToString();
}

我希望在10秒后,将抛出IOException。

使用取消令牌时,期待一个OperationCanceledException。从技术上讲,取消令牌可用于各种取消方案 - 代码决定它不再需要完成操作,用户手动取消操作,或者超时。 OperationCanceledException是通用异常类型,意思是“取消”。

© www.soinside.com 2019 - 2024. All rights reserved.