当任务运行异步方法时,等待所有任务

时间:2018-12-06 00:25:01

标签: c# android xamarin async-await task

我一直试图在等待多个线程时合并几个问题的结果,但是我等待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;
}

我认为这是因为任务包含 async 委托方法?我不希望它们是异步的,但是它们必须是因为PollDownload()等待其他异步方法(尽管在这里可以将它们更改为同步方法,但在此问题的其他情况下,它们不能更改为同步方法。所以我仍然需要一个解决方案。

1 个答案:

答案 0 :(得分:4)

new Task()接受Action,因此您传递的async void不会等待其结果。

您应该改用Task.Run(),它也接受Func<Task>