6

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

Rizwan Khan
  • 293
  • 3
  • 9
  • 17
  • 2
    Is your network connection fully used? If so, you can't speed up the download with multiple threads. – Nick Butler Nov 07 '11 at 12:13
  • 3
    This will not help. This will only add overhead. – Marc Gravell Nov 07 '11 at 12:13
  • 1
    Why assume that is the client side/bandwidth that is the problem? It can help if the web server uses some sort of throttling that doesn't check if multiple connections are from the same client. – jgauffin Nov 07 '11 at 12:15
  • 1
    @NicholasButler it can help is the server only seeds at X speed per connection. – pjvds Nov 07 '11 at 12:25

3 Answers3

4

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)

Community
  • 1
  • 1
jgauffin
  • 99,844
  • 45
  • 235
  • 372
4

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.

zmilojko
  • 2,125
  • 17
  • 27
2

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.

pjvds
  • 938
  • 6
  • 11