[英]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.