Dar
Dar

Reputation: 23

c# awaitable task staying in the same context

Here is what I have:

My implementation:

The method is implemented as:

async Task DoSomething()
{
  // code
  await // async();
  // code
}

and that works fine

How do I resolve this - return an awaitable task that is not async and stays on the same thread/context?

Upvotes: 2

Views: 1013

Answers (1)

Niyoko
Niyoko

Reputation: 7662

You should use return Task.FromResult(returnValueHere). It will be slightly faster and will stay in the same thread. And don't forget to remove async from the method declaration.

If your method returns nothing, you can also simply use return Task.FromResult(0).

public Task DoSomething()
{
    // Work done here
    return Task.FromResult(0);
}

Upvotes: 4

Related Questions