如果 HttpClient 不应该用于using声明,请参阅以下链接:https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/ http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/
因此,如果您不应该在 using 语句中使用 HttpClient 那么为什么那么多示例将 WebClient 放在 using 语句中(包括 Microsoft);我还没有看到一篇关于不将 WebClient 放入using陈述?最终,在最低级别,WebClient 和 HttpClient 在同一位置打开 TCP/IP 套接字。是否是中间的原因使得 WebClient 可以接受放入using陈述?
注意我问这个问题是有原因的:我有一个在 WinXP、Win7 完整版和嵌入式系统上运行的客户端应用程序,我用来将 XML 发布到后端主机(CentOS 系统)的代码如下所示:
void PostXml(string url, string xml, int id) {
try
{
//Console.WriteLine("POST Request: " + xml);
using (WebClient wc = new WebClient())
{
wc.Proxy = null; //DEBUG: testing this to see if it helps webclient post failure after time x
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
Byte[] d = Encoding.ASCII.GetBytes(xml);
//however Async below is better regardless for closing app and non interference with GUI
//Byte[] res = web.UploadData(url, "POST", d); //sychrounous will block until sent and response returned
wc.UploadDataCompleted += new UploadDataCompletedEventHandler(web_UploadDataCompleted);
wc.UploadDataAsync(new Uri(url), "POST", d, id);
}
}
catch (WebException ex)
{
string responseText = "";
using (var reader = new StreamReader(ex.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
string logMsg = DateTime.Now.ToString("s") + " - PostXml WebClient webexception: " + ex.Message + "\r\n" +
" response: " + responseText + "\r\n\r\n";
File.AppendAllText(SPUClient.frmMain._logFile, logMsg);
}
catch (Exception ex) {
//Console.WriteLine("PostXml Exception: " + ex.Message);
string logMsg = DateTime.Now.ToString("s") + " - PostXml exception: " + ex.Message + "\r\n";
File.AppendAllText(SPUClient.frmMain._logFile, logMsg);
}
}
PostXml 每 1 分钟被调用 2 次,我在该领域有 400 个客户端运行上面的代码,其中一些已经运行了一年多没有错误。但是我们有一些客户端在运行几周或几个月后运行此代码,显然只是停止执行 UploadDataAsync("POST")?目前我们所知道的是我们没有遇到异常,POST 消息不会离开计算机,并且在我的 CentOS 日志文件中我可以看到它从未到达(CentOS 上的 domain.net.access.log 显示了所有来自我所有客户的 POST 连接)。请记住,这种情况很少发生,有些客户端从未失败过,有些客户端在这种情况发生之前运行了数月/数周。重新启动客户端应用程序当然可以解决问题。我应该在 using 语句中使用 WebClient 这可能是导致此问题的原因还是其他原因?