I'm stuck in something I thought so simple that it drives me out of myself.
I need to declare a Task in some point and run it later, I thought of:
Task T1 { get; set; }
public async Task CreateAndAwaitAsync()
{
T1 = new Task(() => {
// time consuming work like:
System.Threading.Thread.Sleep(1000);
}
await T1;
}
Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1
I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!
So, yes, you can await already completed tasks. Note that, if you call await several time, it will return it every time and by reference if it's not a value.
If it is some trivial operation that executes quickly, then you can just call it synchronously, without the need for await . But if it is a long-running operation, you may need to find a way to make it asynchronous.
If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.
C# Language Async-Await Returning a Task without await There is only one asynchronous call inside the method. The asynchronous call is at the end of the method. Catching/handling exception that may happen within the Task is not necessary.
I thought it can be answered in comment but better to provide more info.
await
means "wait for this task to complete, then do the rest stuff". Task from your example is not started. await
will not start it for you, so the whole method will just stuck at await
until you start the task.
Even with your current code, if you later do T1.Start()
- it will run your lambda and after it is completed - your task returned by CreateAndAwaitAsync
will also complete.
Otherwise - either start task right when creating it (Task.Run
) or just return Task
directly without any async\await:
public Task CreateAndAwaitAsync()
{
T1 = new Task(() => {
// time consuming work like:
System.Threading.Thread.Sleep(1000);
}
// if you need to start it somewhere, do T1.Start();
return T1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With