【发布时间】:2014-07-24 07:07:24
【问题描述】:
我不确定是我做错了什么还是 Dataflow 有问题,但是当Receive() 抛出异常时我无法解决。 当我运行这个测试时:
public class AsyncProblem
{
[Fact]
public void AsyncVsAwaiterProblem()
{
var max = 1000;
var noOfExceptions = 0;
for (int i = 0; i < max; i++)
{
try
{
Await().Wait();
}
catch
{
noOfExceptions++;
}
}
Assert.Equal(max,noOfExceptions);
}
public async Task Await()
{
bool firstPassed = false;
var divideBlock = new TransformBlock<int, int>((x) =>
{
if (firstPassed)
throw new ArgumentException("error");
firstPassed = true;
return 0;
});
divideBlock.Post(2);
divideBlock.Post(3); // this should cause failure;
divideBlock.Complete();
while (await divideBlock.OutputAvailableAsync())
{
var value = divideBlock.Receive(); // this should throw exception on second call
}
try
{
divideBlock.Completion.Wait();
}
catch
{
}
}
}
我得到的结果不一致,第一次运行:
Xunit.Sdk.EqualExceptionAssert.Equal() Failure
Expected: 1000
Actual: 127
然后再次运行:
Xunit.Sdk.EqualExceptionAssert.Equal() Failure
Expected: 1000
Actual: 14
有人可以确认这不是“在我的机器上”唯一的问题吗?
【问题讨论】:
-
noOfExceptions不是线程安全的。尝试使用Interlocked.Increment。 -
谢谢,但是这段代码是连续的 - Wait() 确保当前任务已经完成。
标签: c# async-await tpl-dataflow