gpt4 book ai didi

c# - .NET 4.0 中任务中的 PostAsync() 导致 WebException

转载 作者:太空狗 更新时间:2023-10-29 23:39:07 26 4
gpt4 key购买 nike

以下方法的目标是异步设置并触发从桌面应用程序到 Web Controller 的 http post。我认为我们如何设置下面的任务一定有问题,我相信 .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;
}
}
}
});
}

该方法有时只能工作 2-3 次,有时是几次,有时甚至对数百个帖子(几批处理)都有效,然后才会失败。程序继续运行,但数据库中没有反射(reflect)更多的帖子,最终抛出异常。 (可能是由于超时。)

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

System.AggregateException was unhandled
Message: An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
Additional information: One or more errors occurred.

有一个内部异常(exception):

_innerException {"The request was canceled"}    System.Exception {System.Net.WebException}

有趣的是,虽然数据库更新在 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;
}

我还应该提到,我们已经尝试将 try/catch 放在几个安排中,但似乎无法在任何地方捕获该异常,直到它冒出并中断运行时。

(最初似乎上面的代码在我们的开发计算机上运行,​​在生产机器上失败,但事实证明这是偶然的运气加上我们的误解。)

最佳答案

这段代码好像已经解决了.....

    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());
}

关于c# - .NET 4.0 中任务中的 PostAsync() 导致 WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21266507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com