【发布时间】:2014-11-22 01:13:12
【问题描述】:
我有一个基于计划运行各种作业的 Windows 服务。在确定要运行哪些作业之后,调度对象的列表被发送到迭代列表并运行每个作业的方法。问题是由于外部数据库调用,某些作业可能需要长达 10 分钟才能运行。
我的目标是不让一项工作阻止其他人排队,基本上一次运行不止一次。我认为使用 async 和 await 可以解决这个问题,但我以前从未使用过这些。
当前代码:
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 会等待作业完成,然后再将控制权交还给循环,而不是允许所有作业开始。
我有两个问题:
- 高级 - aysnc/await 是最佳选择,还是应该使用其他方法?
- 需要更新哪些内容以允许循环在不阻塞的情况下启动所有作业,但在所有作业完成之前不允许函数返回?
【问题讨论】:
标签: c# .net multithreading asynchronous async-await