我有三个顶级进程,我想同时运行。在两个进程完成后,我有需要运行的子进程,一个是需要并发运行的集合。我面临的唯一问题是,在子进程完成之前,刷新最终会执行。我插入了一些跟踪语句,结果是:
Pulling AssetList
Pulling MarketImports
Pulling AccountBalance
AccountBalance Pulled
MarketImports Pulled
Pulling WalletTransactions
AssetList Pulled
Pulling BlueprintList
Pulling MarketOrders
Pulling IndustryJobs
Flushing
MarketOrders Pulled
BlueprintList Pulled
IndustryJobs Pulled
WalletTransactions Pulled如何在子进程完成后进行刷新?有关守则如下:
private async Task DoPull(string token, string name, Func<string, Task> func)
{
Trace.WriteLine(string.Format("Pulling {0}", name));
await func(token);
StopSteps(token, name);
Trace.WriteLine(string.Format("{0} Pulled", name));
}
try
{
await Task.WhenAll(
DoPull(tk, "AssetList", _assetMapper.Pull).ContinueWith(async c => await Task.WhenAll(
DoPull(tk, "BlueprintList", _blueprintMapper.Pull),
DoPull(tk, "MarketOrders", _orderMapper.Pull),
DoPull(tk, "IndustryJobs", _jobMapper.Pull))),
DoPull(tk, "MarketImports", _marketMapper.Pull).ContinueWith(async c =>
await DoPull(tk, "WalletTransactions", _transactionMapper.Pull)),
DoPull(tk, "AccountBalance", _balanceMapper.Pull));
}
catch (Exception)
{
StopSteps(token, _running.ToArray());
}
finally { Flush(token); }发布于 2015-06-13 00:36:49
实答案
在DoPull中,等待的函数完成后,执行将返回给调用方。这意味着,一旦其他所有的等待在其他DoPull调用中完成,它将继续在主方法中返回,并命中finally块。在这种情况发生之前,不能保证StopSteps或Trace.WriteLine调用会执行。
不正确
ContinueWith内部的处决在任何地方都没有被期待。
您应该使用ContinueWith<Task>来获得该功能。
而且,这是很难跟随所有的内联这样的事情,也许打破它的一点,所以它更容易确定步骤是什么?
private async Task Method()
{
try
{
var assetList = DoPull(tk, "AssetList", _assetMapper.Pull)
.ContinueWith<Task>(t => Task.WhenAll(
DoPull(tk, "BlueprintList", _blueprintMapper.Pull),
DoPull(tk, "MarketOrders", _orderMapper.Pull),
DoPull(tk, "IndustryJobs", _jobMapper.Pull));
var marketImport = DoPull(tk, "MarketImports", _marketMapper.Pull)
.ContinueWith<Task>(t => DoPull(tk, "WalletTransactions", _transactionMapper.Pull));
var accountBalance = DoPull(tk, "AccountBalance", _balanceMapper.Pull);
await Task.WhenAll(assetList, marketImport, accountBalance);
}
catch (Exception)
{
StopSteps(token, _running.ToArray());
}
finally { Flush(token); }
}编辑
private async Task PullAssetList()
{
await DoPull(tk, "AssetList", _assetMapper.Pull);
await Task.WhenAll(
DoPull(tk, "BlueprintList", _blueprintMapper.Pull),
DoPull(tk, "MarketOrders", _orderMapper.Pull),
DoPull(tk, "IndustryJobs", _jobMapper.Pull));
}
private async Task PullMarketImport()
{
await DoPull(tk, "MarketImports", _marketMapper.Pull);
await DoPull(tk, "WalletTransactions", _transactionMapper.Pull);
}
private async Task PullAccountBalance()
{
await DoPull(tk, "AccountBalance", _balanceMapper.Pull);
}
private async Task Method()
{
try
{
await Task.WhenAll(PullAssetList(), PullMarketImport(), PullAccountBalance());
}
catch (Exception)
{
StopSteps(token, _running.ToArray());
}
finally { Flush(token); }
}https://stackoverflow.com/questions/30813955
复制相似问题