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'
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. 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.
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. For more on out
: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier