2010-08-03 54 views
2

我有网络请求,我用streamreader读取信息。我想在15秒后在此流媒体播放器后停止播放。因为有时读书过程需要更多时间,但有时会顺利。如果阅读过程需要15秒以上的时间,我该如何阻止它?我打开所有想法。c#几秒钟后停止流式读取器。这可能吗?

+0

澄清:你的意思是等待更多数据15秒后,或连续阅读15秒后停止? – 2010-08-03 14:38:57

+0

我的意思是在等待更多数据15秒后停止。 – 2010-08-03 14:52:03

回答

1

使用System.Threading.Timer并将打勾事件设置为15秒。这不是最干净的,但它会起作用。或者一个秒表

--stopwatch选项

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

     } 

--Timer选项

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

既然你说“网络请求”,我假设t流读取器包装一个System.IO.Stream,您通过调用httpWebRequest.GetResponse().GetResponseStream()HttpWebRequest实例获得。

如果是这样的话,你应该看看HttpWebRequest.ReadWriteTimeout