views:

33

answers:

1

I'm trying to download a lot of files after downloading a sql statement must insert a record. I'm using System.Net.Client to download each file synchronously, still it could be done asynchronous. There's no relation or dependency between each download.

At first I just tried to use WebClient.DownloadFileAsync but that shutted the program down and killed all the download processes/threads. Second I tried to create a wait routine something like this;

while (processedFiles < totalFiles)
         Thread.Sleep(1000)

This freezed everything. So could someone tell me which aproach to take to implement this Async?

A: 

Ideally you would just use DownloadFileAsync, and wire up the DownloadFileCompleted event to notify you when a download has completed. Here is a sample piece of code for how you might wire up the event:

// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground2 (string address)
{
    WebClient client = new WebClient ();
    Uri uri = new Uri(address);

    // Specify that the DownloadFileCallback method gets called
    // when the download completes.
    client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
    // Specify a progress notification handler.
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
    client.DownloadFileAsync (uri, "serverdata.txt");
}

You can call this from a WinForms application, which would just be sitting idle when the downloads are in progress. Then when all downloads have completed you can shut down the program or whatever you need to do.

Justin Ethier
Hi Justin,That was kind of the same code I used. Never the less picture this; I got an array of uri's to download and I do a foreach loop to execute a client.DownloadFileAsync. After the loop finished the whole application closes (like a console application with no pause)
Casper Broeren
Hmm... the download client is designed to work within an application that is handling events. The application needs to sit idle and process events instead of closing. A simple way to do this might be to migrate the app to Windows Forms, and put up some kind of progress dialog while the files are being downloaded.
Justin Ethier