2012-10-02 2 views
0

환경 : Windows CE/.NET Compact FrameWork 3.5.비동기 HTTPWebrequest (시간 초과 포함)

나는 비동기 웹 요청에 대한 시간 제한 기능을 구현

1에서 몇 가지 지침)가 필요합니다. ThreadPool :: RegisterWaitForSingleObject()는 .NetCf에서 사용할 수 없으며 조금 갇혀 있습니다.

2) 네트워크 자체를 사용할 수 없는지 확인하는 방법은 무엇입니까? 구글 검색이 도움이되지 못했습니다.

참고 : .NET Compact FrameWork에서는 ThreadPool :: RegisterWaitForSingleObject를 사용할 수 없습니다.

void StartRequest() 
{ 
    try 
    { 
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.78.221.11/SomeFunc/excpopulatedept"); 
     RqstState myRequestState = new RqstState(); 
     myRequestState.request = myHttpWebRequest; 

     // Start the asynchronous request. 
     IAsyncResult result = 
        (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); 

     // Release the HttpWebResponse resource. 
     myRequestState.response.Close(); 
    } 
    catch (WebException ex) 
    { 
     ; 
    } 
    catch (Exception ex) 
    { 
     ; 
    } 
} 

private void RespCallback(IAsyncResult asynchronousResult) 
{ 
    try 
    { 
     //State of request is asynchronous. 
     RqstState myRequestState = (RqstState)asynchronousResult.AsyncState; 
     HttpWebRequest myHttpWebRequest = myRequestState.request; 
     myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult); 

     // Read the response into a Stream object. 
     Stream responseStream = myRequestState.response.GetResponseStream(); 
     myRequestState.streamResponse = responseStream; 

     // Begin the Reading of the contents of the HTML page and print it to the console. 
     IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState); 
     return; 
    } 
    catch (WebException e) 
    { 
     Console.WriteLine("\nRespCallback Exception raised!"); 
     Console.WriteLine("\nMessage:{0}", e.Message); 
     Console.WriteLine("\nStatus:{0}", e.Status); 
    } 
} 

private void ReadCallBack(IAsyncResult asyncResult) 
{ 
    try 
    { 
     RqstState myRequestState = (RqstState)asyncResult.AsyncState; 
     Stream responseStream = myRequestState.streamResponse; 
     int read = responseStream.EndRead(asyncResult); 
     // Read the HTML page and then print it to the console. 
     if (read > 0) 
     { 
      myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read)); 
      IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState); 
      return; 
     } 
     else 
     { 
      //Console.WriteLine("\nThe contents of the Html page are : "); 
      if (myRequestState.requestData.Length > 1) 
      { 
       string stringContent; 
       stringContent = myRequestState.requestData.ToString(); 
       responseStream.Close(); 
      } 
      catch (WebException e) 
      { 
      } 
     } 
    } 
} 

이 시간 내 주셔서 감사합니다

여기 내 비동기 구현입니다.

+3

의미있는 방식으로 처리하지 않을 예외는 절대로 발견하지 마십시오. –

+0

@Phoenix 먼저 컴파일하는 게시 코드로 시작하는 것이 좋습니다. –

답변

0

Eric J가 언급 한 것을 계속하려면 귀하의 캐치 직전에 myRequestState.response.Close()이 있습니다. 그것은 response이 null이거나 response이 열리지 않기 때문에 거의 입니다.은 예외를 발생시킬 것입니다. 이는 비동기로 BeginGetResponse을 호출하고 사용자가 지정한 콜백이 다음 줄 (response.close)이 호출 될 때 호출되지 않을 가능성이 높기 때문입니다. 예외가 발생하는 이유를 알지 못하기 때문에 예외를 숨기지 않고 해결할 수 있습니다.

기본적으로 타임 아웃이 없으므로 구성 가능한 시간 제한이없는 무언가를 다루기 때문에 타이머를 설정하고 제한 시간이 끝나면 연결을 닫아야합니다. 예 :

HttpWebRequest myHttpWebRequest; // ADDED 
Timer timer; // ADDED 

private void StartRequest() 
{ 
     myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.78.221.11/SomeFunc/excpopulatedept"); 
     RqstState myRequestState = new RqstState(); 
     myRequestState.request = myHttpWebRequest; 

     // Start the asynchronous request. 
     IAsyncResult result = 
        (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); 
      timer = new Timer(delegate { if (!completed) myHttpWebRequest.Abort(); }, null, waitTime, Timeout.Infinite); // ADDED 
} 

//... 

private void ReadCallBack(IAsyncResult asyncResult) 
{ 
    try 
    { 
     RqstState myRequestState = (RqstState)asyncResult.AsyncState; 
     Stream responseStream = myRequestState.streamResponse; 
     int read = responseStream.EndRead(asyncResult); 
     // Read the HTML page and then print it to the console. 
     if (read > 0) 
     { 
      myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read)); 
      IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState); 
     } 
     else 
     { 
      completed = true; // ADDED 
      timer.Dispose(); // ADDED 
      if (myRequestState.requestData.Length > 1) 
      { 
       string stringContent; 
       stringContent = myRequestState.requestData.ToString(); 
       responseStream.Close(); 
      } 
     } 
    } 
} 

난 단지 복사 코드를 붙여, 그래서 원래 제공 무엇으로 컴파일 같은 것, 그러나이 충분히 당신이 올바른 방향으로 가고 얻을이 있어야합니다.

+0

고마워 .. 그게 효과가 ... – Phoenix