[英]Maximum Thread Number
我有用户控件,它有这样的方法
public void DownloadFileAsync()
{
ThreadStart thread = DownloadFile;
Thread downloadThread = new Thread(thread);
downloadThread.Start();
}
在表单中,我有4个用户控件。 但是当我在每个控件的用户控件DownloadFileAsync()中调用时,只有两个控件开始下载。 完成其中一个后,下一个开始下载。
有什么问题以及如何每次下载simultanesly?
感谢您的关注。
public void DownloadFile()
{
int byteRecieved = 0;
byte[] bytes = new byte[_bufferSize];
try
{
_webRequestDownloadFile = (HttpWebRequest)WebRequest.Create(_file.AddressURL);
_webRequestDownloadFile.AddRange((int)_totalRecievedBytes);
_webResponseDownloadFile = (HttpWebResponse)_webRequestDownloadFile.GetResponse();
_fileSize = _webResponseDownloadFile.ContentLength;
_streamFile = _webResponseDownloadFile.GetResponseStream();
_streamLocalFile = new FileStream(_file.LocalDirectory, _totalRecievedBytes > 0 ? FileMode.Append : FileMode.Create);
MessageBox.Show("Salam");
_status = DownloadStatus.Inprogress;
while ((byteRecieved = _streamFile.Read(bytes, 0, _bufferSize)) > 0 && _status == DownloadStatus.Inprogress)
{
_streamLocalFile.Write(bytes, 0, byteRecieved);
_totalRecievedBytes += byteRecieved;
if (_totalRecievedBytes >= _fileSize)
{
argsCompleted.Status = DownloadStatus.Completed;
if (_fileDownloadCompleted != null)
_fileDownloadCompleted(_file, argsCompleted);
break;
}
argsProgress.UpdateEventArgument(DownloadStatus.Inprogress, _totalRecievedBytes);
if (_fileDownloadProgress != null)
_fileDownloadProgress(_file, argsProgress);
}
}
catch (Exception ex)
{
LogOperations.Log(ex.Message);
}
finally
{
_streamFile.Close();
_streamFile.Close();
_streamLocalFile.Close();
_webResponseDownloadFile.Close();
}
}
HTTP在很长一段时间内每个Web Origin限制为2个连接,因此人们不会并行启动太多下载。 这个限制已被取消,但许多实现,包括HttpWebRequest仍然实现它。
来自draft-ietf-httpbis-p1-messaging :
客户端(包括代理)应该限制它们维护到给定服务器(包括代理)的同时连接数。
HTTP的先前版本提供了特定数量的连接作为上限,但发现这对许多应用程序来说是不切实际的。 因此,本规范并未强制要求特定的最大连接数,而是鼓励客户在打开多个连接时保守。
您可以通过设置ConnectionLimit属性来更改连接限制,如下所示:
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
httpWebRequest.ServicePoint.ConnectionLimit = 10;
不要将限制设置得太高,因此不要使服务器过载。
此外,您应该考虑使用WebClient类及其提供的异步方法(例如DownloadDataAsync方法 ),而不是使用线程。 请参阅如何以编程方式删除WebClient中的2连接限制,以了解如何在此处更改连接限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.