加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Task.WhenAll没等

发布时间:2020-12-15 08:09:23 所属栏目:百科 来源:网络整理
导读:我正在学习如何在控制台应用程序中使用异步函数,但无法使Task.WhenAll等到所有任务完成.以下代码有什么问题?它同步工作.先感谢您. static void Main(string[] args){ ... IncluiValores(...); ...}static async void IncluiValores(...){ TaskListint res1
我正在学习如何在控制台应用程序中使用异步函数,但无法使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,那么它确实应该.不要打破链条.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读