Home Task return type with and without Async
Reply: 2

Task return type with and without Async

SharmaPattar
1#
SharmaPattar Published in 2017-12-07 19:37:23Z

This question already has an answer here:

  • What is the purpose of “return await” in C#? 6 answers

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. Please help me.

Jess
2#
Jess Reply to 2017-12-07 19:51:58Z

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.
Immac
3#
Immac Reply to 2017-12-07 19:48:56Z

(...) “async”. This keyword allows that inside the method the word “await” can be used, and modifies how its result is handled by the method. That’s it.

The method runs synchronously until it finds the word “await” and that word is the one that takes care of asynchrony. “Await” is an operator that receives a parameter: an awaitable (an asynchronous operation) behaves in this way:

From here

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304498 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO