HttpClient:使用ObjectContent取消异步HTTP请求

时间:2015-04-17 12:34:55

标签: c# .net dotnet-httpclient

在下面的代码中,Wait()方法永远不会抛出由任务取消引起的异常,并且永远不会将控制返回给调用线程。

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://stackoverflow.com")
    {
        Content = new ObjectContent<Foo>(new Foo(), new JsonMediaTypeFormatter())
    };
    CancellationTokenSource cts = new CancellationTokenSource();
    HttpClient client = new HttpClient();
    Task task = client.SendAsync(request, cts.Token);
    cts.Cancel();
    task.Wait();

但是当request.Content是带有序列化Foo对象的StringContent时,抛出异常。我的期望是所有HttpContent类型都会引发异常。

  1. 为什么不抛出异常?

  2. 创建StringContent的解决方法并不好。也许         还存在另一种解决方法吗?

1 个答案:

答案 0 :(得分:0)

您为任务编写了经典的异步死锁。等待操作将永远不会完成,因为您的线程在“等待”中被阻塞。 您需要等待任务,然后它将按预期工作。取消异常将在等待行上引发。

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://stackoverflow.com")
{
    Content = new ObjectContent<Foo>(new Foo(), new JsonMediaTypeFormatter())
};
CancellationTokenSource cts = new CancellationTokenSource();
HttpClient client = new HttpClient();
Task task = client.SendAsync(request, cts.Token);
cts.Cancel();
await task;
相关问题