2

My Xamarin.Forms app has several interfaces (for Dependencys) with implementations for Android and iOS. The methods in them are not async. Now I want to add the implementations for these interfaces for UWP, but several of the needed methods are async so they don't fit the signatures. How do I deal with this? Is the only solution to create a separate interface for UWP?

ispiro
  • 26,556
  • 38
  • 136
  • 291

2 Answers2

1

In these scenarios I tend to use the Task.FromResult method for the non-async implementations. Example: you have a method on Windows that returns a Task of type bool and you want to implement the same functionality on Android and iOS for methods that return bool.

public interface ISample
{
    public Task<bool> GetABool();
}

On Windows you would just return the Task

public class WindowsSample : ISample
{
    public Task<bool> GetABool()
    {
        // whatever implementation
        return SomeTaskOfTypeBool(); 
    }
}

On Android or iOS you would wrap the value in a Task

public class AndroidSample : ISample
{
    public Task<bool> GetABool()
    {
        // replace with however you get the value.
        var ret = true;
        return Task.FromResult(ret);
    }
}
Will Decker
  • 3,216
  • 20
  • 30
0

You can not use the await keyword. You have to create a new Task and wait for the Task to finish. A separate interface is not necessary. Exception handling with Tasks can be tricky, inform yourself.

Calling an async method Method1 with return value:

string s = Task.Run(() => Method1()).Result;

Without return value:

Task.Run(() => Method1()).Wait;

.Rest or .Wait block until the Task is completed.

More Details: Calling async methods from non-async code

Koseng
  • 34
  • 3