在.NET 4.0中的Task中的PostAsync()导致WebException

RJB*_*RJB 5 c# multithreading http .net-4.0 task-parallel-library

以下方法的目标是异步设置和发布从桌面应用程序到Web控制器的http帖子.我认为我们如何设置下面的任务一定存在问题,我相信.NET 4.5中有更好的实践,例如async/await和Task.Run可以解决问题,但升级目前不是选项.有没有更好的方法来处理/写入.NET 4.0,以防止下面描述的问题?

    public void PostWithoutResponse(object objectToPost, string url) {
        Task.Factory.StartNew(() =>
        {
            using (var handler = new HttpClientHandler()) {
                handler.PreAuthenticate = true;
                handler.Credentials = _credentialPool.GetNetworkCredentials(new Uri(url));
                using (var client = new HttpClient(handler)) {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    using (var stringContent = new StringContent(JsonConvert.SerializeObject(objectToPost), Encoding.UTF8, "application/json")) {
                        // We weren't able to get this post to work without waiting for result
                        var result = client.PostAsync(url, stringContent).Result;
                    }
                }
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

该方法有时只能工作2-3次,有时几次,有时它甚至适用于数百个帖子 - 几个批次 - 在失败之前.程序继续,但数据库中不会反映任何其他帖子,最终会抛出异常.(可能是由于超时.)

我们能够观察到这是抛出的异常:

System.AggregateException was unhandled
Message: An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
Additional information: One or more errors occurred.
Run Code Online (Sandbox Code Playgroud)

有一个内部例外:

_innerException {"The request was canceled"}    System.Exception {System.Net.WebException}
Run Code Online (Sandbox Code Playgroud)

有趣的是,虽然数据库更新在2-3之后停止,但程序(自动批处理工作流程)继续运行,并且在达到此方法以获取新批处理之前似乎不会抛出异常.可能相关?

    public string GetPostResult(object objectToPost, string url) {
        string jsonResult = null;
        using (var handler = new HttpClientHandler()) {
            handler.PreAuthenticate = true;
            handler.Credentials = _credentialPool.GetNetworkCredentials(new Uri(url));
            using (var client = new HttpClient(handler)) {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var serializedContent = JsonConvert.SerializeObject(objectToPost);
                using (var stringContent = new StringContent(serializedContent, Encoding.UTF8, "application/json")) {
                    var taskResult = client.PostAsync(url, stringContent).Result;
                    jsonResult = taskResult.Content.ReadAsStringAsync().Result;
                }
            }
        }
        return jsonResult;
    }
Run Code Online (Sandbox Code Playgroud)

另外我应该提一下,我们已经尝试将try/catch放在几个排列中,但似乎无法在任何地方捕获该异常,直到它冒出并打破运行时.

(最初似乎上面的代码在我们的开发计算机上运行,​​并且在生产机器上失败了,但结果是随机运气加上我们的误解.)

RJB*_*RJB 2

这段代码似乎已经解决了......

    public void PostWithoutResponse(object objectToPost, string url) {
        var uri = new Uri(url);
        var httpPost = (HttpWebRequest)WebRequest.Create(uri);
        httpPost.KeepAlive = false;
        httpPost.Method = "POST";
        httpPost.Credentials = _credentialPool.GetNetworkCredentials(uri);
        httpPost.ContentType = "application/json";
        using (var streamWriter = new StreamWriter(httpPost.GetRequestStream())) {
            var json = JsonConvert.SerializeObject(objectToPost);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        Task.Factory.StartNew(() => httpPost.GetResponse());
    }
Run Code Online (Sandbox Code Playgroud)