I want to download a single file with Multi-Threads in C#. e.g: Thread1 start downloading from 1% to 40%. Thread2 start downloading from 41% to 70%. Thread3 start downloading from 71% to 100%
Please suggest me some code. Thanks in advance
I want to download a single file with Multi-Threads in C#. e.g: Thread1 start downloading from 1% to 40%. Thread2 start downloading from 41% to 70%. Thread3 start downloading from 71% to 100%
Please suggest me some code. Thanks in advance
You do it by using the Range HTTP header. Download each part to a seperate file and merge them when done (to avoid multi threading issues)
Update
The easiest way is to use one HttpWebRequest
per thread. Read the answer here: HttpWebRequest or WebRequest - Resume Download ASP.NET
To merge the files, simply read them in sequence and write to a new file (using FileStream
class)
How about using HttpRequest class, with AddRange method called. This should a header with offset from which to start downloading.
var request = HttpWebRequest.Create(new Uri("http://www.myurl.com/hugefile"));
request.Method = "GET";
request.AddRange(offset_for_this_thread); // I assume you have calculated this
// before firing threads
Stream reponseStream = request.GetResponse().GetResponseStream();
You can then read from ´responseStream´ the data and merge it with the other threads once it is done.
However, as noticed by everybody else, this will only bring value if you have two adapters, both connected to internet, and you have some kind of bandwidth balancing between those adapter... Otherwise Windows wil likely divert everything to the same connection.
The AddRange
allows you to download only range. This will set the range HTTP header field which will tell the server you are only interested in a certain range. Multiple ranges are allowed.
Some people mentioned that this method isn't useful and will only add overhead. Imho this depends on the situation, their are servers that only seed at speed X per connection. Some will filter on IP, other only on the active connection. So in some situations your scenario would work.