2012-09-28 156 views
0

我正在visual studio上使用Windows Phone使用c#。我正在使用一個線程,在線程完成後我需要調用該函數,但是我的問題是線程中有一個http調用,所以線程會在http調用結束之前進入完成階段。我只需要在http調用結束時結束線程。但是現在線程在調用http調用之後結束,所以我怎麼能克服這個問題,謝謝。這裏是我的代碼等待HTTP請求完成

void worker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    Deployment.Current.Dispatcher.BeginInvoke(() => 
    { 
     handle.MakeRequest(WidgetsCallBack, WidgetsErrorCallBack, 
          DeviceInfo.DeviceId, ApplicationSettings.Apikey); 
    }); 
} 

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    // function which i should call only after the thread is completed. 
    // (http cll should also be ended) 
} 
+1

請將所有的手機改爲手機,巨大的差異 – EaterOfCode

回答

0

沒有看到http調用你讓我相信你正在做一個異步的。所以,如果你想在不同的線程中運行http調用,那麼你可以使用任何一種異步方法(例如DownloadStringAsync)。所以,你不需要一個線程來實現這一點。這有幫助嗎?

更新基於下面的評論提供的示例代碼:

因此,而不是一個工人,我會用一個WebClient的對象,並以異步方式調用網址:

// Creating the client object: 
WebClient wc = new WebClient(); 

// Registering a handler to the async request completed event. The Handler method is HandleRequest and is wrapped: 
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(HandleRequest); 

// Setting some header information (just to illustrate how to do it): 
wc.Headers["Accept"] = "application/json"; 

// Making the actual call to a given URL: 
wc.DownloadStringAsync(new Uri("http://stackoverflow.com")); 

處理器方法的定義如下:

void HandleRequest(object sender, DownloadStringCompletedEventArgs e) 
{ 
    if (!e.Cancelled && e.Error == null) 
    { 
     // Handle e.Result as there are no issues: 
     ... 
    } 
} 
+0

是的我是mak一個異步線程。我sae鏈接提供可以請詳細解釋我如何在這裏使用它? – user1665577

+0

當然我更新了我的答案以回覆您的評論。 –