[英]Unclear about compiler error when using “out” in async-await block in C#
I have a method I'm calling and I want to make sure it absolutely finishes before continuing. 我有一个正在调用的方法,我想确保在继续之前它绝对完成。 I'm also interested in knowing if it completed successfully or not, so I'm doing the following:
我也想知道它是否成功完成,所以我正在做以下事情:
async void Foo() {
bool success;
// stuff
await Task.Run(
() => Bar(out success)
);
if (!success) { // this is the line causing the compiler-error
// handle
}
// other stuff
}
void Bar(out bool success);
But I'm getting error 但是我出错了
CS0165 Use of unassigned local variable 'success'
CS0165使用未分配的局部变量“成功”
This isn't a huge deal, as I can get cute and initialize success=false
and pass it as ref
instead of out
and that seems to work as desired. 这不是什么大不了的事情,因为我可以变得很可爱,并初始化
success=false
并将其作为ref
而不是out
传递out
,这似乎可以按需工作。 However, I'm curious about what the intricacies of async-await
(or Task.Run
) are that seem to lead to a case that doesn't guarantee out success
will be properly assigned. 但是,我对
async-await
(或Task.Run
)的复杂性似乎导致无法保证out success
分配正确案例的情况感到好奇。
Any enlightenment is appreciated! 任何启发,感激不尽!
Edit: 编辑:
To add a bit more context, the following block compiles and executes fine. 要添加更多上下文,以下块可以编译并执行。
void Caller() {
bool success;
Callee(out success);
if (success) {
// do something
}
}
void Callee();
This is because out
parameters are not required to be initialized before being passed. 这是因为
out
参数在传递之前不需要初始化。 For more on out
: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier 有关更多信息,请
out
: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/out-parameter-modifier
Consider the following possible (though totally incorrect) implementation of Task.Run
: 考虑以下可能的
Task.Run
实现(尽管完全不正确):
public class Task
{
public static Task Run(Action action)
{
return Task.Delay(500);
}
//...
}
Now think about the code in question. 现在考虑有问题的代码。 With this implementation of
Task.Run
, will the Bar
method ever get called? 通过
Task.Run
这种实现,是否会调用Bar
方法? No. Therefore success
will never get initialized, and an attempt to access an uninitialized variable is made. 否。因此,
success
永远不会被初始化,因此会尝试访问未初始化的变量。
The compiler has no idea about the real implementation of Task.Run
or what it will do. 编译器不知道
Task.Run
的实际实现或其作用。 It can't assume that it isn't implemented like I have above, and therefore an uninitialized variable is possible. 不能假设它没有像我上面那样实现,因此可能有未初始化的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.