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

c# – 异步和等待与循环

发布时间:2020-12-15 17:50:12 所属栏目:百科 来源:网络整理
导读:参见英文答案 Using async/await for multiple tasks3 我有一个Windows服务,根据计划运行各种工作.在确定要运行哪些作业之后,会将一个调度对象列表发送到迭代列表并运行每个作业的方法.问题是由于外部数据库调用,某些作业最多可能需要10分钟才能运行. 我的目
参见英文答案 > Using async/await for multiple tasks3
我有一个Windows服务,根据计划运行各种工作.在确定要运行哪些作业之后,会将一个调度对象列表发送到迭代列表并运行每个作业的方法.问题是由于外部数据库调用,某些作业最多可能需要10分钟才能运行.

我的目标是没有一个工作阻止其他人排队,基本上一次有多个运行.我以为使用异步和等待可以解决这个问题,但是我从来没有使用过这些.

当前代码:

public static bool Load(List<Schedule> scheduleList)
{
    foreach (Schedule schedule in scheduleList)
    {
        Load(schedule.ScheduleId);
    }

    return true;
}

public static bool Load(int scheduleId)
{
    // make database and other external resource calls 
    // some jobs run for up to 10 minutes   

    return true;
}

我尝试更新到这段代码:

public async static Task<bool> LoadAsync(List<Schedule> scheduleList)
{
    foreach (Schedule schedule in scheduleList)
    {
        bool result = await LoadAsync((int)schedule.JobId,schedule.ScheduleId);
    }

    return true;
}

public async static Task<bool> LoadAsync(int scheduleId)
{
    // make database and other external resource calls 
    // some jobs run for up to 10 minutes   

    return true;
}

问题是第一个LoadAsync等待作业完成,然后再将控制权重新回到循环,而不是允许所有作业启动.

我有两个问题:

>高级 – 是否等待最佳选择,还是应该采用不同的方法?
>什么需要更新以允许循环启动所有的作业而不阻止,但不允许该功能返回,直到所有作业完成?

解决方法

High Level – Are async/await the best choice,or should I use a different approach?

异步等待是您尝试做的完美的,同时卸载多个IO绑定任务.

What needs to be updated to allow the loop to kick off all the jobs without blocking,but not allow the function to return until all jobs are completed?

您的循环当前等待,因为您等待每次调用LoadAsync.你想要的是同时执行它们,而不是等待所有的人完成使用Task.WhenAll:

public async static Task<bool> LoadAsync(List<Schedule> scheduleList)
{
   var scheduleTaskList = scheduleList.Select(schedule => 
                          LoadAsync((int)schedule.JobId,schedule.ScheduleId)).ToList();
   await Task.WhenAll(scheduleTaskList);

   return true;
}

(编辑:李大同)

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

    推荐文章
      热点阅读