我想製作多線程異步下載管理器。但是我有多線程問題。 一個線程正常工作,但是當我創建第二個線程時 - 什麼都不工作。 我認爲webrequest的同步問題。我讀了這個回答Multithreading a large number of web requests in c#,但我完全不明白。現在問題:我如何修改代碼以使用多線程(線程,線程池)。webrequests c多線程程序#
類DownloadableContent
:
{
private string url { get; set; }
private string path { get; set; }
private Stream streamResponse { get; set; }
private Stream streamLocal { get; set; }
private HttpWebRequest webRequest { get; set; }
private HttpWebResponse webResponse { get; set; }
public DownloadableContent(string url, string path)
{
this.url = url;
this.path = path;
}
public void Download()
{
using (WebClient wcDownload = new WebClient())
{
try
{
webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
streamResponse = wcDownload.OpenRead(url);
streamLocal = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
byte[] downBuffer = new byte[2048];
int bytesSize = 0;
while ((bytesSize = streamResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
streamLocal.Write(downBuffer, 0, bytesSize);
}
}
finally
{
streamResponse.Close();
streamLocal.Close();
}
}
}
}
而且main
類:
DownloadableContent file = new DownloadableContent("url", @"path");
Thread thread = new Thread(file.Download);
thread.Start();
你的代碼很混亂。你正在使用'WebClient' *和*'HttpWebRequest'。因此,您正在爲每個網址提出兩個請求。您應該刪除'webRequest'和'webResponse',並使用'WebClient'。 – 2014-09-26 16:23:28
很可能你遇到問題的原因是你沒有處理你正在創建的'webRequest'和'webResponse'對象。我從經驗中知道,這往往會導致事情在幾個請求後停止工作。由於您沒有使用它們,只需將它們從代碼中移除即可。 – 2014-09-26 16:25:09
我只在代碼中留下了'Webclient',現在效果很好 – 2014-09-27 15:37:28