2012-07-10 20 views
4

我無法按照示例獲取回調。不要從BeginGetResponse接收回調

我有以下代碼:

private void startWebRequest(object sender, EventArgs e) 
    { 
     Uri url = new Uri("http://localhost.com/dummyGet"); 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 
     request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request); 
    } 

    private void ReadWebRequestCallback(IAsyncResult callbackResult) 
    { 
     Console.WriteLine("Don not get here"); 
     try 
     { 
      var req = (HttpWebRequest)callbackResult.AsyncState; 
      using (var response = req.EndGetResponse(callbackResult)) 
      { 
       Console.WriteLine("Code"); 
      } 
     } 
     catch 
     { } 
    } 

我一直BANGIN我的頭這一切的一天,我可以看到在我的瀏覽器的GET請求,或在提琴手/ Wireshark的客戶端。但代碼(ReadWebRequestCallback)不會被調用。

編輯: 還要注意的是,如果我使用Web客戶端和DownloadStringAsync它的工作原理,但我需要比404和200:

_client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted); 
_client.DownloadStringAsync(_concurrentCheckUrl); 
} 

private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    {// Works, gets here} 
+0

試着繞過request.BeginGetResponse,看看是否有一些異常提出 – 2012-07-10 15:24:18

+0

看起來好像不會引發異常。 – Nitro 2012-07-10 15:33:17

+0

考慮到你用一個空的'catch {}'吞下任何異常,你怎麼知道它沒有進入ReadWebRequest? – user7116 2012-07-10 15:33:57

回答

0

非常感謝所有的幫助!

我最終做了這樣的工作,如Simplify Async networking with Tasks in SL5中所述的任務。

HttpWebRequest _request; 

private void doGetRequest() 
    _request = WebRequestCreator.ClientHttp.Create(new Uri("http://localhost/getDummy")) as HttpWebRequest; 
     var webTask = Task.Factory.FromAsync<WebResponse> 
      (_request.BeginGetResponse, _request.EndGetResponse, null) 
      .ContinueWith(
      task => 
      { 
       var response = (HttpWebResponse)task.Result; 
       // The reason I use HttpRequest, not WebRequest, to get statuscode. 
       if (response.StatusCode == HttpStatusCode.ServiceUnavailable) 
       { 
        //Do Stuff 
       } 
      }); 

然而,我認爲這個問題依賴於我的日誌沒有登錄時,它是在回調,這我無法理解。但是,在我將頭撞向牆壁一天之後,我會把它留下。但認爲我的實際職位會工作。

1

其他HTTP狀態代碼,我不知道如果這是解決方案,但是在回調調用之前關閉的擁有線程?作爲silverlight我懷疑它,但我想我會提出來。

檢查http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx - 注意

ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true); 

    // The response came in the allowed time. The work processing will happen in the 
    // callback function. 
    allDone.WaitOne(); 

這可能是你應該嘗試什麼過了Thread.Sleep。如果這不是問題,您是否可以通過添加斷點或其他輸出語句來確保代碼永遠不會被觸發?

+0

這也是我最好的猜測。在發出呼叫後,讓線程休眠幾秒鐘,即作爲startWebRequest()中的最後一行。我的意思只是要找出它是否是一個線程問題。 – matcheek 2012-07-10 15:54:57

+0

預期結果應該是什麼?現在已經添加了30秒的Thread.Sleep(新的Timespan(0,0,30)),但唯一發生的是視頻的開始被延遲。 – Nitro 2012-07-10 16:19:01

+0

線程睡眠可以讓請求完成它的工作,但是如果直接跟在睡眠之後的語句導致退出,它不會被激發。線程是棘手的,微軟的新模式肯定會推向前列。誰調用了「startWebRequest」? – 2012-07-10 19:09:45