How to set time out for http client request operation in windows phone 8.1/Windows 8.1

大憨熊 提交于 2019-12-08 15:16:47

问题


How to set Timeout property to Windows.Web.Http.HttpClient operation. The code sample I used is below.

public HttpClient httpClient;
public CancellationTokenSource cts;

public void SendRequest(addressUri,postrequestbody)
{
    HttpHelper.CreateHttpClient(ref httpClient);
    cts = new CancellationTokenSource();
    HttpRequestMessage msg = 
        new HttpRequestMessage(new HttpMethod("POST"), 
                               new Uri(addressUri));
    msg.Content = new HttpStringContent(postrequestbody);
    msg.Content.Headers.ContentType = 
        new HttpMediaTypeHeaderValue("application/json");
    HttpResponseMessage response = 
        await httpClient.SendRequestAsync(msg).AsTask();

    if (response.StatusCode == HttpStatusCode.Ok)
    {
    }
}

回答1:


Use a CancellationToken:

try 
{
    CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await
        client.SendRequestAsync(request).AsTask(cts.Token);
}
catch (TaskCanceledException ex)
{
    // Catch operation aborted ...
}


来源:https://stackoverflow.com/questions/28060575/how-to-set-time-out-for-http-client-request-operation-in-windows-phone-8-1-windo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!