【发布时间】:2019-03-13 09:43:40
【问题描述】:
关于从async 方法返回是否总是产生释放语义以及await 是否总是产生获取语义,我找不到明确的答案。我认为是的,否则任何async/await 代码都会是雷区?
下面是一个例子:返回值是否都保证为100*2 和12345*2,没有任何明确的锁或障碍?
private static async Task<(int, int)> AMethod()
{
// Runs on the original thread:
var x = 100;
var y = 12345;
var task = Task.Run(() =>
{
// Can run on another thread:
x *= 2;
y *= 2;
// Implicit return here, marking the task completed.
// Release semantics or not?
});
await task; // Acquire semantics or not?
// Runs on the original thread:
return (x, y);
}
编辑:当然,Task.Run 还需要在开始运行任务代码时生成发布和获取。忘记了原始问题中的那些。
【问题讨论】:
-
添加
await task.ConfigureAwait(false)。然后你绝对不能保证 x 和 y 将是100*2和12345*2 -
@YauhenSampir 不,这对问题没有任何影响。
-
@YauhenSampir 如果发布和获取都在那里,那么无论
.ConfigureAwait(false)如何,您仍然会得到一个不错的结果。如果没有,它已经被破坏了。
标签: c# .net async-await language-lawyer memory-model