2010-08-03 5 views
2

웹 요청이있어서 streamreader로 정보를 읽습니다. 15 초 후이 유출입선에서 멈추고 싶습니다. 때로는 독서 과정에 시간이 더 걸리기도하지만 때로는 잘 진행되기도합니다. 독서 과정에 15 초 이상 걸리는 경우 어떻게 멈출 수 있습니까? 나는 모든 아이디어를 열었습니다.몇 초 후 C#으로 스트림 리더를 중지합니다. 이것이 가능한가?

+0

명확화 : 15 초 동안 더 많은 데이터를 기다렸거나 15 초 동안 계속 읽은 후 중지하겠습니까? –

+0

15 초 후에 더 많은 데이터를 기다리고 있습니다. –

답변

1

System.Threading.Timer를 사용하고 15 초 동안 on tick 이벤트를 설정하십시오. 가장 깨끗한 것은 아니지만 효과가있을 것입니다. 아니면 스톱워치

--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

"웹 요청"이라고 말하면서 hat 스트림 리더는 HttpWebRequest 인스턴스에서 얻은 System.IO.StreamhttpWebRequest.GetResponse().GetResponseStream()으로 호출하여 래핑합니다.

그런 경우라면 HttpWebRequest.ReadWriteTimeout을 살펴 봐야합니다.

관련 문제