2013-10-23 58 views

回答

14

您可以使用CancellationTokenSource以超時超時選項。

 HttpClient client = new HttpClient(); 
     var cancellationTokenSource = new CancellationTokenSource(2000); //timeout 
     try 
     { 
      var response = await client.GetAsync("https://test.example.com", cancellationTokenSource.Token); 
     } 
     catch (TaskCanceledException ex) 
     { 

     } 

編輯: 隨着Windows.Web.Http.HttpClient你應該使用AsTask()擴展方法:

HttpClient client = new HttpClient(); 
System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000); 
try 
{ 
    client.GetAsync(new Uri("http://example.com")).AsTask(source.Token); 
} 
catch(TaskCanceledException ex) 
{ 

} 
+0

我的錯誤,上面的示例使用System.Net.Http.HttpClient寫。如果您需要堅持使用Windows.Web.HttpClient,您可能需要查看http://msdn.microsoft.com/en-us/library/windows/apps/windows.web.http.filters.aspx –

+0

「Windows.Web.Http.HttpClient」CancellationTokenSource中提供了相同的實現。 –

+0

真的嗎?原因GetAsync需要一個HttpCompletionOption。我無法傳遞令牌。 – Naning