我有以下代码:
static async Task TestTwo()
{
int x = 0;
// The table writer is going to be faster
var ab = new ActionBlock<int>(async item =>
{
await Task.Delay(30);
Interlocked.Increment(ref x);
},
new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 1, BoundedCapacity = 10 });
await MyObservable().ForEachAsync(async i =>
{
await ab.SendAsync(i); // if the ActionBlock is full, this will complete when it has some room
});
await Task.Delay(10); // just to let it get ahead a little
ab.Complete();
await ab.Completion; // all items proccess by action block
Console.WriteLine("Test two {0}", x);
}
static IObservable<int> MyObservable()
{
return Observable.Create<int>(async o =>
{
for (int i = 0; i < 500; i++)
{
await Task.Delay(10);
o.OnNext(i);
}
o.OnCompleted();
});
}
这将输出 241 ,但是如果我将await ab.SendAsync(i)
更改为ab.SendAsync(i).Wait()
,则它将输出 500 。我猜这是由于它只是继续而已,它将在await ab.SendAsync(i)
之后运行任何代码。我希望从ForEachAsync
返回的等待也将等待它调用的所有内容。
我想念什么吗?