实现与NetworkStream.BeginRead和NetworkStream.EndRead超时 [英] Implementing a timeout with NetworkStream.BeginRead and NetworkStream.EndRead

查看:3017
本文介绍了实现与NetworkStream.BeginRead和NetworkStream.EndRead超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了下面的函数中使用,以实现一个超时功能的NetworkStream 的异步读取功能(BeginRead的 <$ C C $>和 EndRead )。它工作正常,直到我注释掉行 Trace.WriteLine(读取动作:+读取动作); 。为什么呢?

I've written the following function to implement a timeout feature using NetworkStream's asynchronous read functions (BeginRead and EndRead). It works fine until I comment out the line Trace.WriteLine("bytesRead: " + bytesRead);. Why?

private int SynchronousRead(byte[] buffer, int count)
{
    int bytesRead = 0;
    bool success = false;
    IAsyncResult result = null;

    result = _stream.BeginRead(
        buffer, 0, count,
        delegate(IAsyncResult r)
        {
            bytesRead = _stream.EndRead(r);
        },
        null);

    success = result.AsyncWaitHandle.WaitOne(_ioTmeoutInMilliseconds, false);

    if (!success)
    {
        throw new TimeoutException("Could not read in the specfied timeout.");
    }

    //If I remove this line, bytesRead is always 0
    Trace.WriteLine("bytesRead: " + bytesRead);

    return bytesRead;
}

以防万一你想知道,我必须这样做,因为我最终需要针对.NET Compact Framework的3.5,它不支持 NetworkStream.ReadTimeout NetworkStream.WriteTimeout 属性。

推荐答案

这是有趣的线程错误。在读取动作变量分配的的等待句柄发出信号。有两件事情可能出错:该方法返回转让前作出。或者线程读取陈旧的价值,因为他们是经过了WaitOne()调用无记忆障碍。 trace语句解决了这个问题,因为它延缓了主线程足够长的时间允许写入变量。它有一个内部锁,以确保高速缓存是一致的。

An interesting threading bug. The bytesRead variable is assigned after the wait handle is signaled. Two things can go wrong: the method returns before the assignment is made. Or the thread reads a stale value since their is no memory barrier past the WaitOne() call. The Trace statement fixes the problem because it delays the main thread long enough to allow the variable to be written. And it has an internal lock that ensures the cache is coherent.

您需要的是读取动作变量信号写入额外的AutoResetEvent。

You'll need an additional AutoResetEvent that signals that bytesRead variable was written.

这篇关于实现与NetworkStream.BeginRead和NetworkStream.EndRead超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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