[英]Wait for all tasks when tasks run async methods
我一直在嘗試在等待多個線程時合並幾個問題的結果,但是我的電話等待Task.WhenAll(Tasks);
在所有任務完成之前通過!
List<Task> tasks = new List<Task>();
foreach (DownloadingFile file in downloadingFiles)
{
Task t = new Task(async delegate { await file.PollDownload(); } );
tasks.Add(t);
t.Start();
}
await Task.WhenAll(tasks);
internal async Task PollDownload()
{
string localFile = "pathToDestination";
WebRequest headerRequest = WebRequest.Create(uri);
headerRequest.Method = "HEAD";
HttpWebResponse response = null;
try
{
response = (HttpWebResponse) await headerRequest.GetResponseAsync();
}
catch
{
Thread.Sleep(500);
try
{
response = (HttpWebResponse)await headerRequest.GetResponseAsync();
}
catch
{
response = null;
}
}
if (response == null)
{
state = DOWNLOAD_STATE.FAILED;
return;
}
totalBytes = response.ContentLength;
state = DOWNLOAD_STATE.WAITING_START;
//Check to see whether a local copy of the remote file exists
if (File.Exists(localFile))
{
DateTime localFileUpdated = File.GetCreationTimeUtc(localFile);
DateTime onlineFileUpdated = response.LastModified;
// If the download date of the local file comes after the modification date of the remote copy
// then we do not need to take any further action here.
if (onlineFileUpdated <= localFileUpdated)
{
state = DOWNLOAD_STATE.SKIPPED;
}
//Otherwise we should remove the local copy and proceed with the download
else
{
File.Delete(localFile);
}
}
return;
}
我認為這是因為任務包含異步委托方法? 我不希望它們是異步的,但是它們必須是因為PollDownload()
等待其他異步方法(盡管在這里可以將它們更改為同步方法,但在此問題的另一個實例中不能將它們更改為同步方法,所以我仍然需要解決方案)。
new Task()
接受一個Action
,因此您傳遞了一個不等待其結果的async void
。
您應該改用Task.Run(),它也接受Func<Task>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.