Reputation: 3067
I have an asynchronous task that is conditional. I want to await it if it's called, but, obviously, not wait for it if it's not.
This is what I tried.
Task l;
if(condition)
{
l = MyProcessAsync();
}
//do other stuff here
if(condition)
{
await Task.WhenAll(l); //unassigned variable error
}
I get Use of unassigned local variable 'l'
compiler error.
What's the appropriate way to do this?
Upvotes: 0
Views: 1106
Reputation: 142158
As far as I know C# does not analyze if conditions in if
statement are the same. Next code will work cause actually there will not be any branching at all generated by compiler:
Task l;
if (1==1) // or if(true)
{
l = Task.CompletedTask;
}
//do other stuff here
if (1==1) // or if(true)
{
await Task.WhenAll(l); //unassigned variable error
}
So in you code you need to initialize local variable, cause using an unassigned local has high likelihood of being a bug (also see this section of specification), so you need to initialize it for example to null
or Task.CompletedTask
from the get-go:
Task l = null; // or Task l = Task.CompletedTask;
Upvotes: 2
Reputation: 406
In your example, you have not assigned to Task l;
.
You need to at least assign it to null.
Here is a working sample in a console application:
static async Task Main(string[] args)
{
var condition = true;
Task task = null;
if (condition)
{
task = MyProcessAsync();
}
Console.WriteLine("Do other stuff");
if (task != null)
{
await task;
}
Console.WriteLine("Finished");
Console.ReadLine();
}
static async Task MyProcessAsync()
{
await Task.Delay(2000);
Console.WriteLine("After async process");
}
Outputs:
Do other stuff
After async process
Finished
Upvotes: 6