【发布时间】:2016-08-24 20:25:07
【问题描述】:
我有以下代码,其中我在 GroupBy 子句中使用了 async 关键字,但是智能告诉我这个调用不会等待并将同步运行,我的问题是我对 GetAllLanguages 的两次调用和GetAllStores 和我随后对 Task.WaitAll(languagesTask, storesTask); 的调用使用异步功能,或者我的所有代码都会同步运行,因为我不等待 GroupBy 语句。也可以等待.GroupBy(async resourceApplicationType .. 电话。
public async Task UpdateAllResources()
{
var applicationTypes = databaseSettings.Select(dbcs => dbcs.ResourceApplicationType);
var commandsPerApplication = applicationTypes
.GroupBy(async resourceApplicationType =>
{
var languagesTask = GetAllLanguages(resourceApplicationType);
var storesTask = GetAllStores(resourceApplicationType);
var resourceCategory = ResourceApplicationToCategoriesMapper.Map(resourceApplicationType);
Task.WaitAll(languagesTask, storesTask);
var commands = from category in resourceCategory
from language in languagesTask.Result
from store in storesTask.Result
select new UpdateResourcesCommand
{
ApplicationType = resourceApplicationType,
StoreCode = store.Code,
LocaleCode = language.Locale,
ResourceCategory = category
};
return new
{
applicationType = resourceApplicationType, commands
};
});
commandsPerApplication.ForEach(commandsGroup =>
{
commandsGroup.Key.Result.commands.ForEach(async command =>
{
await commandExecutor.Execute<UpdateResourcesCommand, Task>(command);
});
});
}
private Task<IEnumerable<Language>> GetAllLanguages(ResourceApplication applicationType)
{
return allLanguagesQueryRetriever.GetByComponentName(InstanceName.GetUniqueName<IAllLanguagesQuery>(applicationType.ToString()))
.Execute(new AllLanguagesCriteria());
}
private Task<IEnumerable<Store>> GetAllStores(ResourceApplication applicationType)
{
return allStoresQueryRetriever
.GetByComponentName(InstanceName.GetUniqueName<IAllStoresQuery>(applicationType.ToString()))
.Execute(new AllStoresCriteria());
}
【问题讨论】:
-
您没有在
UpdateAllResources函数中等待Task.WaitAll(languagesTask, storesTask);。这可能意味着在您尝试访问结果之前任务尚未完成 -
@JLevett 该语句不可等待“类型 void 不可等待”,它本质上是在等待。
-
我很抱歉。你也可以使用
await Task.WhenAll() -
出于好奇,Threads 窗口 Debug-> Windows-> Threads 显示什么?
标签: c# linq async-await