2

我有网络请求,我用流式阅读器阅读信息。我想在 15 秒后在这个流媒体阅读器之后停下来。因为有时阅读过程需要更多时间,但有时进展顺利。如果阅读过程需要超过 15 秒的时间,我该如何停止?我对所有想法持开放态度。

4

3 回答 3

2

既然你说“网络请求”,我假设流阅读器包装你通过调用System.IO.Stream从实例中获得的.HttpWebRequesthttpWebRequest.GetResponse().GetResponseStream()

If that's the case, you should take a look at HttpWebRequest.ReadWriteTimeout.

于 2010-08-03T14:56:49.080 回答
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;
    }
于 2010-08-03T14:41:24.363 回答
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
}
于 2010-08-03T14:43:24.173 回答