Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a Task Property and awaiting it

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!

like image 564
Shockwaver Avatar asked Mar 29 '17 14:03

Shockwaver


People also ask

Can you await a completed Task?

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.

Does Task run need to be awaited?

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.

What happens if you don't await a Task?

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.

How do I return a Task without await?

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.


1 Answers

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;
}
like image 97
Evk Avatar answered Sep 26 '22 15:09

Evk