gpt4 book ai didi

c# - 每次我下载文件时,WebClient 都会打开一个新连接,并且所有连接都保持建立状态

转载 作者:可可西里 更新时间:2023-11-01 08:37:45 26 4
gpt4 key购买 nike

我在寻找如何关闭 WebClient 建立的连接时遇到了问题。我创建了一个新的 WebClient 对象,然后多次调用 DownloadFile 方法,但是,它总是为每次调用创建一个新连接,并且这些连接保持打开状态(已建立状态) ,我可以在 TCPView 中看到所有已建立的连接。

如果当我处理 Webclient 时,它们保持已建立状态,那更让我烦恼的是什么......?如何在下载完成后强制关闭连接?

我已经尝试派生 WebClient 并手动将 keep alive 设置为 false,我的应用程序配置也允许足够的连接。

<connectionManagement>
<add address="*" maxconnection="1000"/>
</connectionManagement>

最佳答案

简短回答:您不需要手动关闭连接。它们在幕后为您管理。

HTTP/1.1 连接不会在请求完成后立即关闭,以便更及时有效地处理对同一服务器的多个请求(例如 Web 浏览器从单个站点请求多个文件)。您不必为此担心或手动关闭它们,因为它们会在一段时间后超时。是否导致错误?

如果这是一个问题,您可以尝试继承 WebClient 并覆盖 GetWebRequest 方法以手动设置 KeepAlive,例如:

public class NoKeepAlivesWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
((HttpWebRequest)request).KeepAlive = false;
}

return request;
}
}

我也总是建议对 WebClient 使用 using 模式:

using (var client = new NoKeepAlivesWebClient())
{
// Some code
}

最后,这里有一些关于 HTTP/1.1 中持久连接的 RFC 信息:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html

还有一个更友好的维基百科条目:

http://en.wikipedia.org/wiki/HTTP_persistent_connection

编辑:

抱歉。我从您编辑的问题中看到您已经尝试过类似上述的方法,但没有成功。

但是,我无法重现您的问题。根据 TCPView,我使用 NoKeepAlivesWebClient 编写了一个小程序,它在使用后成功关闭了连接。

static void Main(string[] args)
{
// Random test URLs
var urls = new List<string> {
"http://msdn.microsoft.com/en-us/library/tt0f69eh.aspx",
"http://msdn.microsoft.com/en-us/library/system.net.webclient.allowreadstreambuffering.aspx",
"http://msdn.microsoft.com/en-us/library/system.net.webclient.allowwritestreambuffering.aspx",
"http://msdn.microsoft.com/en-us/library/system.net.webclient.baseaddress.aspx",
"http://msdn.microsoft.com/en-us/library/system.net.webclient.cachepolicy.aspx",
"http://msdn.microsoft.com/en-us/library/system.net.webclient.credentials.aspx",
"https://www.youtube.com/",
"https://www.youtube.com/feed/UClTpDNIOtgfRkyT-AFGNWVw",
"https://www.youtube.com/feed/UCj_UmpoD8Ph_EcyN_xEXrUQ",
"https://www.youtube.com/channel/UCn-K7GIs62ENvdQe6ZZk9-w" };

using (var client = new NoKeepAlivesWebClient())
{
// Save each URL to a Temp file
foreach (var url in urls)
{
client.DownloadFile(new Uri(url), System.IO.Path.GetTempFileName());
Console.WriteLine("Downloaded: " + url);
}
}
}

这里还有一个关于同一问题的 SO 问题:

C# get rid of Connection header in WebClient

关于c# - 每次我下载文件时,WebClient 都会打开一个新连接,并且所有连接都保持建立状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16501845/

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