iNc0ming
iNc0ming

Reputation: 383

.net 4.5 async syntax

I wrote the code below,

Task.Factory.StartNew<int>(async () =>
        {
            await Task.Delay(1000);
            return 42;
        });

but the read line appeared under the "async" keyword, and the code cannot compiled due to some syntax error, can anybody advise me what to do?

Thx a lot!

Upvotes: 3

Views: 274

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456437

You probably want to use Task.Run, which has more natural syntax for async lambdas:

var task = Task.Run(async () =>
{
  await Task.Delay(1000);
  return 42;
});

Upvotes: 5

Mario S
Mario S

Reputation: 11945

You have to return a Task<T>, like so:

Task.Factory.StartNew<Task<int>>(async () =>
{
    await Task.Delay(1000);
    return 42;
});

The async keyword requires to return Task, Task<T> or void. Read more about it: async (C# Reference).

Upvotes: 2

Related Questions