-1

ファイルのURLを解析するforeachがあります。各サイクルの終わりにファイルをダウンロードしたいのですが、今のところ、すべてのファイルがダウンロードされます。ダウンロードの終了時にUIスレッド(foreachが含まれている)をブロックする方法を理解する必要があります。

私が今持っているもの:

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();
  });
}

それで、DownloadFileAsyncが終了する間UI thradを待ってから、私の大きな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 に答える