Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface where one of the implementations needs to be async

I have an interface, which delivers me a certain path. In one of my implementations I need to use async, but I haven't figured out how to get the result of an async method into a synchronous method. Here is the code sample:

Interface:

public interface IFilePath
{
    string GetAsset();
}

Problematic implementation:

public class FilePath : IFilePath
{
    public string GetAsset()
    {
        return GetAssetAssync();
    }

    private async Task<string> GetAssetAssync()
    {
        StorageFolder assetsFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets").AsTask().ConfigureAwait(false);
        return assetsFolder.Path;
    }
}

Only for this implementation I need the async call. All others do not need it. So I can't use public Task<string> GetAsset() or can I somehow?

like image 521
testing Avatar asked Mar 16 '16 13:03

testing


1 Answers

A Task-returning method indicates that the implementation may be asynchronous. So, the best approach is to update your interface to allow asynchronous implementations:

public interface IFilePath
{
  Task<string> GetAssetAsync();
}

I would attempt to make the other implementations asynchronous (file I/O is a naturally asynchronous operation), but if you have truly synchronous implementations (e.g., reading from an in-memory zip file or something), then you can wrap your result in Task.FromResult:

class SynchronousFilePath: IFilePath
{
  public string GetAsset(); // natural synchronous implementation

  public Task<string> GetAssetAsync()
  {
    return Task.FromResult(GetAsset());
  }
}
like image 177
Stephen Cleary Avatar answered Sep 23 '22 18:09

Stephen Cleary