ispiro
ispiro

Reputation: 27713

How to deal with UWP async when Android and iOS are not async?

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?

Upvotes: 2

Views: 105

Answers (2)

Will Decker
Will Decker

Reputation: 3266

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

Upvotes: 1

Koseng
Koseng

Reputation: 44

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

Upvotes: 0

Related Questions