我通过lambda表达式创建一批匿名函数。我想使用TaskId来区分匿名函数。 这是代码:
int count = 3;
int i;
for (int j = 0; j < 10; j++)
{
i = 0;
Func<bool, Task<int>> func = async (b) =>
{
return j;
};
while (i++ < count)
{
var task = func(true);
Console.WriteLine(String.Format("Task Result:{0} TaskId:{1}",
task.Result, task.Id));
}
}
这是输出
Task Result:0 TaskId:1
Task Result:0 TaskId:1
Task Result:0 TaskId:1
Task Result:1 TaskId:2
Task Result:1 TaskId:2
Task Result:1 TaskId:2
Task Result:2 TaskId:3
Task Result:2 TaskId:3
Task Result:2 TaskId:3
Task Result:3 TaskId:4
Task Result:3 TaskId:4
Task Result:3 TaskId:4
Task Result:4 TaskId:5
Task Result:4 TaskId:5
Task Result:4 TaskId:5
Task Result:5 TaskId:6
Task Result:5 TaskId:6
Task Result:5 TaskId:6
Task Result:6 TaskId:7
Task Result:6 TaskId:7
Task Result:6 TaskId:7
Task Result:7 TaskId:8
Task Result:7 TaskId:8
Task Result:7 TaskId:8
Task Result:8 TaskId:9
Task Result:8 TaskId:9
Task Result:8 TaskId:9
Task Result:9 TaskId:10
Task Result:9 TaskId:11
Task Result:9 TaskId:12
正如您所看到的,由于结果大于8,因此TaskId发生了变化。我想知道这种现象的原因。谢谢你的帮助:)
答案 0 :(得分:2)
本身不是编译器,而是正在进行缓存的.NET框架。查看编译器用于管理异步方法生成的状态机的AsyncMethodBuilder
代码。看起来SetResult
在GetTaskForResult
中执行了一些缓存。有一些非常具体的代码用于缓存基本值类型,包括:
// For Int32, we cache a range of common values, e.g. [-1,4).
else if (typeof(TResult) == typeof(Int32))
{
// Compare to constants to avoid static field access if outside of cached range.
// We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the
// lower side, due to positive values being more common than negative as return values.
Int32 value = (Int32)(object)result;
if (value < AsyncTaskCache.EXCLUSIVE_INT32_MAX &&
value >= AsyncTaskCache.INCLUSIVE_INT32_MIN)
{
Task<Int32> task = AsyncTaskCache.Int32Tasks[value - AsyncTaskCache.INCLUSIVE_INT32_MIN];
return JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed
}
}
我们看到了:
/// <summary>The minimum value, inclusive, for which we want a cached task.</summary>
internal const Int32 INCLUSIVE_INT32_MIN = -1;
/// <summary>The maximum value, exclusive, for which we want a cached task.</summary>
internal const Int32 EXCLUSIVE_INT32_MAX = 9;
这就是为什么8是神奇的截止。值得注意的是-1也应该被缓存,并且从我的测试开始。
答案 1 :(得分:0)
ambda表达式存储变量而不是值。你的表达式是异步的,所以我认为线程搞砸了结果。尝试没有异步魔法,它会显示正确的结果。