2010-08-03 50 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