Marius Istudor
Marius Istudor

Reputation: 165

DownloadFIleCompleted and DownloadProgressChanged not firing in a multithread win forms application

I'm having a problem using the WebClient events in a multi threaded application (DownloadFileCompleted and DownloadProgressChanged). I have the main method in which I created a timer. At an interval, I will create a thread that will popup another windows form (DownloaderForm) if a condition is met.

void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e) {
    var thread = new Thread(SilentCheckingUpdate) {
        Name = "Update Checker",
    };
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

The SilentChekingUpdate method checks for update.

bool found = _updater.UpdateRequired(currentConfig, out latestVersion);

if (found)
{
    _updater.ShowUpdateUI(latestVersion); 
}

If found, it calls another method from win forms class Updater which calss the StartDownload from Downloader.

public void ShowUpdateUI(Item currentItem)
{
    var downloader = new Downloader();
    downloader.StartDownload();
}

The downloader contains an WebBrowserControl. I made a method that calls DownloadFileAsync.

public void StartDownload()
{          
    // start async download
    var client = new WebClient();

    client.DownloadProgressChanged += ClientDownloadProgressChanged;
    client.DownloadFileCompleted += ClientDownloadFileCompleted;
    var url = new Uri(_item.DownloadLink);

    client.DownloadFileAsync(url, _tempName);
}

Everything works fine and events are fired if I call that StartDownload function from the form thread. When i use the worker thread for StartDownload from TimerElapsed, DownloadFileAsync's events are not fired anymore.

Can you help me?

Thank you!

Upvotes: 0

Views: 1440

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35869

It's unclear why you're starting a thread that basically just calls DownloadFileAsync--which downloads a file async. If DownloadFileAsync is async, there's not much reason to start another thread to call it.

One think I would look at is that you're creating a local client object in your StartDownload method. This almost immediately lets client go out of scope and potentially lets the GC collect it. If that happened, it could lead to problems. Maybe making client a member field might help; but, that's a guess.

You haven't provided the code "that works*, so it's really hard to tell why there's a difference.

Upvotes: 2

Related Questions