2
votes

Here is what I have:

  • a multi-platform (Xamarin/C#) application

  • an interface that defines a method (for a UI task) that has platform specific implementations

  • on one platform the implementation needs to await some async calls, on the other one - it does not

My implementation:

  • the interface defines the method as: Task DoSomething()

  • on the platform where the implementation has to await async calls

The method is implemented as:

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

and that works fine

  • on the platform where the implementation does not call other async methods I have 2 options:

    1. define the method as async Task DoSomething() and get a compile time warning "This async method lacks 'await' operators and will run synchronously..."

    2. define the method as Task DoSomething() that returns Task.Run(() => { /main logic here/}), however when I call await DoSomething() - the main logic is executed on another thread, which I don't want to happen. With the implementation in (1) calling await DoSomething stays on the same thread.

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

1

1 Answers

4
votes

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);
}