I want to make multithreading asynchronous download manager. But i have problems with multithreading. One thread correctly works, but when I create second thread - works nothing. I assume that a problem with synchronism of webrequest. I read this answer Multithreading a large number of web requests in c#, but I didn't understand completely. Now question: How can I modify a code to use a multithreading(Thread, Threadpool).
class 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();
}
}
}
}
And class main
:
DownloadableContent file = new DownloadableContent("url", @"path");
Thread thread = new Thread(file.Download);
thread.Start();