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?
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With