应该在using语句中使用WebClient吗?

时间:2018-10-12 21:24:49

标签: c# httpclient webclient using

如果不应该在 using 语句中使用HttpClient,请参见以下链接: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ 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 POST到后端主机(CentOS系统)的代码如下:< / p>

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,这可能是导致此问题的原因还是其他原因?

0 个答案:

没有答案