3

我正在尝试使用 HttpClient 使用以下代码将消息异步记录到 REST 服务:

public void LogMessage(string operationURI, string message, EventLogEntryType logEntryType)
        {
            using (var client = new HttpClient())
            {
                var cancellationToken = new CancellationToken();
                client.SendAsync(GetRequest(operationURI), cancellationToken).ContinueWith(
                    cw =>
                    {
                        var response = cw.Result; //(I get an error on this line)
                        if (!response.IsSuccessStatusCode)
                        {
                            LogMessageLocal(message, logEntryType);
                        }
                    });
            }
        }

注意:GetRequestMessage 返回一个 HttpRequestMessage。

但我收到一条错误消息,指出“任务已取消。”

有任何想法吗?

4

2 回答 2

2

我相信当超过超时时会发生这种情况。您可以检查您的timeout,并记录在异常之前它未完成的时间,以查看它是否被超过。

于 2012-12-31T15:12:13.120 回答
0

HttpClient 在 SendAsync 完成之前被释放。这会导致 aTaskCanceledException被抛出。

  1. async关键字添加到LogMessage.
  2. 添加await关键字SendAsync并将其结果设置为var response.
  3. 等待响应后,对响应做任何你想做的事情。
于 2015-12-28T13:35:33.790 回答