Windows.Web.Http.HttpClient超时选项

时间:2013-10-23 07:04:46

标签: windows-runtime windows-store-apps

由于SSL证书问题,我们在我的应用服务层使用“Windows.Web.Http.HttpClient”API。

我在下面提到了我的项目样本。

http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664

我们如何在“Windows.Web.Http.HttpClient”API中实现超时选项

1 个答案:

答案 0 :(得分:13)

您可以使用具有超时的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)
{

}