-1

I have foreach, that parses out file URL. At the end of each cycle I want to download the file, but, as I have it now, it downloads all of them. I need to figure out how to block UI thread (that has foreach in it) while download finishes.

What I have now:

foreach (... in ...)
{
  //some code that extracts FileURL and fileName
  downloadFile(FileURL, fileName)
  //should wait here, without blocking UI
  //are.WaitOne(); //this blocks the UI
}

AutoResetEvent are = new AutoResetEvent(false);
void downloadFile(String FileURL, String fileName)
{
  Thread bgThread = new Thread(() =>
  {
    WebClient FileClient = new WebClient();
    FileClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FileClient_DownloadProgressChanged);
    FileClient.DownloadFileCompleted += new AsyncCompletedEventHandler(FileClient_DownloadFileCompleted);
    FileClient.DownloadFileAsync(new Uri(FileURL), fileName);
  //should wait here, without blocking UI
  //are.WaitOne(); //this either downloads one, or both in paralel.
  });
  bgThread.Start();

}

void FileClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  this.BeginInvoke((MethodInvoker)delegate
  {
    label5.Text = String.Format("Downloaded {0} of {1} bytes...", e.BytesReceived.ToString(), e.TotalBytesToReceive.ToString());
    progressBar1.Value = e.ProgressPercentage;
  });
}

void FileClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
  this.BeginInvoke((MethodInvoker)delegate
  {
    label5.Text = "Done.";
    //stop the waiting
    are.Set();
  });
}

So, is there a way to wait for UI thrad while DownloadFileAsync finishes, and then continue with my big foreach?

4

1 回答 1

0

你可以这样做:

List<Task> tasks = new List<Task>();
foreach(....)
{

Thread bgThread = new Thread(() =>
  {
    WebClient FileClient = new WebClient();
    FileClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FileClient_DownloadProgressChanged);
    FileClient.DownloadFileCompleted += new AsyncCompletedEventHandler(FileClient_DownloadFileCompleted);
    FileClient.DownloadFileAsync(new Uri(FileURL), fileName);
  //should wait here, without blocking UI
  //are.WaitOne(); //this either downloads one, or both in paralel.
  });
  bgThread.Start();

    tasks.Add(bgThread);


}

var arr = tasks.ToArray();
Task.WaitAll(arr);
于 2013-03-14T20:59:37.213 回答