c#几秒后停止一个流读取器。这可能吗?

时间:2010-08-03 14:35:36

标签: c# httprequest streamreader

我有网络请求,我使用streamreader读取信息。 15秒之后我想在这个流重读器之后停下来。因为有时阅读过程需要更多时间,但有时候进展顺利。如果阅读过程花费的时间超过15秒,我怎么能阻止它?我打开所有的想法。

3 个答案:

答案 0 :(得分:2)

由于您说“网络请求”,我假设流阅读器通过调用System.IO.Stream来包装您从HttpWebRequest实例获得的httpWebRequest.GetResponse().GetResponseStream()

如果是这种情况,您应该查看HttpWebRequest.ReadWriteTimeout

答案 1 :(得分:1)

使用System.Threading.Timer并设置on tick事件15秒。它不是最干净但它会起作用。或者也许是秒表

- 秒表选项

        Stopwatch sw = new Stopwatch();
        sw.Start();
        while (raeder.Read() && sw.ElapsedMilliseconds < 15000)
        {

        }

- 计时器选项

        Timer t = new Timer();
        t.Interval = 15000;
        t.Elapsed += new ElapsedEventHandler(t_Elapsed);
        t.Start();
        read = true;
        while (raeder.Read() && read)
        {

        }
    }

    private bool read;
    void t_Elapsed(object sender, ElapsedEventArgs e)
    {
        read = false;
    }

答案 2 :(得分:0)

您必须在另一个线程中运行该任务,并从主线程监视它是否运行超过15秒:

string result;
Action asyncAction = () =>
{
    //do stuff
    Thread.Sleep(10000); // some long running operation
    result = "I'm finished"; // put the result there
};

// have some var that holds the value
bool done = false;
// invoke the action on another thread, and when done: set done to true
asyncAction.BeginInvoke((res)=>done=true, null);

int msProceeded = 0;
while(!done)
{
    Thread.Sleep(100); // do nothing
    msProceeded += 100;

    if (msProceeded > 5000) break; // when we proceed 5 secs break out of this loop
}

// done holds the status, and result holds the result
if(!done)
{
    //aborted
}
else
{
    //finished
    Console.WriteLine(result); // prints I'm finished, if it's executed fast enough
}