tags:

views:

275

answers:

2

Hi Everyone,

I'm a bit confused why the event doesn't fire when the file has downloaded.

The file it self downloads perfectly fine.

I'm assuming there is some error in the way I am using this, in that the event doesn't fire inside a loop.

Thanks for any help anyone can give me

class DownloadQueue
{
    public List<string[]> DownloadItems { get; set; }
    public int CurrentDownloads;
    public int DownloadInProgress;
    string url = @"http://www.google.co.uk/intl/en_uk/images/logo.gif";
    bool downloadComplete;

    public DownloadQueue()
    {
        CurrentDownloads = 0;
        DownloadItems = new List<string[]>();
        Console.Write("new download queue made");
    }

    public void startDownloading(int maxSimulatiousDownloads)
    {
        downloadComplete = true;
        DownloadInProgress = 0;
        WebClient client = new WebClient();
        client.DownloadFileCompleted +=
                    new AsyncCompletedEventHandler(this.downloadCompleteMethod);


            while(DownloadInProgress != DownloadItems.Count )
            {
                if (downloadComplete == true)
                {
                    downloadComplete = false;          

                    client.DownloadFileAsync(new Uri(DownloadItems.ElementAt(DownloadInProgress).ElementAt(0).ToString()), DownloadItems.ElementAt(DownloadInProgress).ElementAt(1).ToString());                        
                }
            }
        Console.Write("all downloads completed");
    }

    private void downloadCompleteMethod(object sender, AsyncCompletedEventArgs e)
    {            
        downloadComplete = true;
        DownloadInProgress++;
        Console.Write("file Downloaded");
    }

    }
A: 

Where are you waiting for the DownloadFileAsync() call to complete? How about something like

manualResetEvent AllDone = new mre(false)

just before console.WriteLine

AllDone.WaitOne()

And in download complete

if (interlocked.decrement(ref downloadComplete) == 0) { AllDone.Set(); }
No Refunds No Returns
A: 

Most likely there is no time for the message to come. I suspect if you put an Application.DoEvents at the end of your loop, it would start firing the events. It is less than ideal to use it, but with the design you have, I can't think of a better way.

Rick Mogstad