如何并行处理多个异步任务foreach循环

How to parallel process multiple async task foreach loop

如何在 forach each 循环中同时处理多个任务,isconnected 由 await item.GetIsConnected() 调用设置。目前刷新速度较慢,希望他们同时处理

之前:

private async void Refresh()
{
    foreach (var item in Cars.ToList<Carnet>())
    {
        await item.GetIsConnected();
        if (item.IsConnected)
        {
            await item.GetCarDetailsAsync();
        }
    }
}

之后:

private async void Refresh()
{
    List<Task> listOfTasks = new List<Task>();
    foreach (var item in Cars.ToList<Carnet>())
    {
        listOfTasks.Add(item.GetIsConnected());
        if (item.IsConnected)
        {
            await item.GetCarDetailsAsync();
        }
    }
    await Task.WhenAll(listOfTasks);
}

由于您没有在 AFTER 示例中等待对 GetIsConnected() 的调用,因此循环将继续,并且可能会或可能不会检查值一旦对 GetIsConnected() 的调用完成,我想你想要做的是添加另一个 return 类型 Task 的方法,然后让该方法调用 GetIsConnected()await 它在方法中,然后在必要时调用 GetCarDetailsAsync()

//changed to return type of Task, as async void should be avoided
//unless this is an event handler method
private async Task Refresh()
//private async void Refresh() //change to this if event handler
{
    List<Task> listOfTasks = new List<Task>();
    foreach (var item in Cars.ToList<Carnet>())
    {
        listOfTasks.Add(GetCarDetails(item));        
    }
    await Task.WhenAll(listOfTasks).ConfigureAwait(false);
}

//method to await the call to GetIsConnect() 
//and then call GetCarDetailsAsync() if necessary
private async Task GetCarDetails(Carnet c)
{
    await c.GetIsConnected();
    if (c.IsConnected)
    {
        await c.GetCarDetailsAsync();
    }
}