cs0815
cs0815

Reputation: 17388

asynch lambda does not producing expected result

I have this code:

static void Main(string[] args)
{
    Func<Task<string>> getWordAsync = async () => "hello";

    Console.WriteLine(getWordAsync());

    Console.ReadLine();
}

Taken from this book. Should this not print:

"hello"

instead of:

System.Threading.Tasks.Task`1[System.String]

Upvotes: 0

Views: 67

Answers (2)

Carles Company
Carles Company

Reputation: 7216

To get the result of an async function you need to use the await keyword. Another options is to get the Result property of the Task object.

Upvotes: 4

user1228
user1228

Reputation:

DO NOT LOOK BEHIND THE CURTAIN!

The async/await keywords are not actually part of the common language specification (upon which the CLR is based), but are an artifact of the compiler. The compiler rewrites your lambda to NOT return a string but in fact to return a Task<string>. You should be able to see this clearly because

() => "hello" 

is a Func<string> that returns a System.String on execution, whereas your variable is of type

Func<Task<string>>

Or, a Func<T> that, when executes, returns a Task<string>.

So, when you execute the func, the return result is a

System.Threading.Tasks.Task`1[System.String]

(the Task`1[System.String] is exemplary of how generic types output their generic parameters)

So, the line

Console.WriteLine(getWordAsync());

is calling ToString() on an object of type Task<string>, which prints out the type's name. This is expected.

The Task is actually running on a different thread, so you'll need to do one of the following to get out the result of the task:

Console.WriteLine(await getWordAsync());

(you must mark your Main method as async prior to using this version) or

Console.WriteLine(getWordAsync().Result);

The second will block the current thread until the result is available. The first will execute the Console method on a different thread when the result becomes available. That's another step down the async/await rabbit hole, btw.

Upvotes: 4

Related Questions