Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task return type with and without Async [duplicate]

I little bit confused on the behavior of the async keyword.

Lets say I have 2 methods,

public async Task DoSomething1()
{
    await Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

And

public Task DoSomething2()
{
    return Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

From my understanding both methods are awaitable. But when I write a method that has a Task return type without the async keyword I need to return a Task otherwise the compiler generates an error. Its a common thing that a method should return its type. But when I use it with the async keyword the compiler generates another error that you can't return a Task. So what does it mean? I am totally confused here.

like image 292
SharmaPattar Avatar asked Dec 07 '17 19:12

SharmaPattar


People also ask

Can we use task without async?

If you use await in your code, you are required to use the async keyword on the method. If you use async and want to return an actual type, you can declare that your method returns the type as a generic Task like this Task<int> . Task<TResult> , for an async method that returns a value.

What is the return type of async task?

Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler. Starting with C# 7.0, any type that has an accessible GetAwaiter method.

Can we use task without async in C#?

C# Language Async-Await Returning a Task without awaitMethods that perform asynchronous operations don't need to use await if: 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.

What is the return type of async await?

The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.


Video Answer


1 Answers

If you use await in your code, you are required to use the async keyword on the method.

If you use async and want to return an actual type, you can return the type as a generic Task like this Task<int>.

Here are the valid return types for an async method:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types

  1. Task<TResult>, for an async method that returns a value.
  2. Task, for an async method that performs an operation but returns no value.
  3. void, for an event handler.
like image 151
Jess Avatar answered Nov 05 '22 17:11

Jess