c# – Task.WhenAll没等

前端之家收集整理的这篇文章主要介绍了c# – Task.WhenAll没等前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习如何在控制台应用程序中使用异步函数,但无法使Task.WhenAll等到所有任务完成.以下代码有什么问题?它同步工作.先感谢您.
static void Main(string[] args)
{
    ...
    IncluiValores(...);
    ...
}

static async void IncluiValores(...)
{
    Task<List<int>> res1 = att.GetAIDBAPI(att);
    Task<List<int>> res2 = att.GetAIDBAPI(att2);

    List<int>[] res = await Task.WhenAll(res1,res2);

    ...
}

更新 – 功能定义:

public async Task<List<int>> GetAIDBAPI(Attributes attributes)
    {

        List<int> results = null;

        Connections client0 = new Connections();
        HttpClient client = client0.OpenAPIConnection(attributes.User[0],attributes.Pwd,attributes.Server,attributes.Chave,attributes.Server2);
        HttpResponseMessage response = await client.PostAsJsonAsync("api/Attributes/ID/Bulk",attributes);

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<dynamic>(content).ToObject<List<int>>();
        }
        else
        {
            var content = "[{-1}]";
            var result = JsonConvert.DeserializeObject<dynamic>(content);
            results = result.ToObject<List<int>>();
        }

        return results;

    }

更新2 – 单独的上下文

static void Main(string[] args)
{
    AsyncContext.Run(() => MainAsync(args));
}

static async void MainAsync(string[] args)
{
    await IncluiValores(...);
}

static async Task IncluiValores(...)
{
    Task<List<int>> res1 = att.GetAIDBAPI(att);
    Task<List<int>> res2 = att.GetAIDBAPI(att2);

    List<int>[] res = await Task.WhenAll(res1,res2); // <- Error here 
    //Collection was modified; enumeration operation may not execute
    ...
}
//Tried to change to code below but it does not wait.
static async Task IncluiValores(...)
{
    Task<List<int>> res1 = att.GetAIDBAPI(att);
    Task<List<int>> res2 = att.GetAIDBAPI(att2);

    await Task.WhenAll(res1,res2); // <- No error,just doesn't wait. 
    list.Add(res1.Result[0]);
}

解决方法

您正在调用异步void方法,这本身就意味着您无法等待结果.无论何时省略等待,都会破坏同步链.该操作实际上是异步发生的,而不是通过await“重新同步”.控件返回给调用者,而(将来的某个时间)操作将异步恢复.

记住,等待是回归.只有await的一致使用才能为您提供同步.停止使用async void – 将其更改为async Task并确保正确等待结果.您的MainAsync方法也是如此.任务是异步方法的缺失.

只有一种情况,你应该看到async void,这是在遗留框架的事件处理程序的同步上下文中(例如在Winforms中).如果async方法可以返回一个Task,那么它确实应该.不要打破链条.

原文链接:https://www.f2er.com/csharp/100921.html

猜你在找的C#相关文章