我有foreach,解析文件URL。在每个周期结束时,我想下载文件,但是,就像我现在一样,它会下载所有文件。我需要弄清楚如何在下载完成时阻止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?
答案 0 :(得分: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);