Application
I have a View Model that is referenced by multiple projects or Views.
Due to the API, some of the View projects are async and others are not.
The View project injects it's implementation of an interface into the View Model using an IOC container.
Code
Consider this minimal example of the code
The interface:
public interface IDatabase
{
Task<Data> GetData();
}
The View Model awaits the GetData method:
public class DisplayDataViewModel
{
private readonly IDatabase _database
public DisplayDataViewModel(IDatabase database)
{
_database = database;
}
private async Task GetDataFromDatabase()
{
Data data = await _database.GetData();
// do something with data...
}
}
Asynchronous View project uses an Async function to get the data
public class AsynchronousViewDataBase : IDatabase
{
public async Task<Data> GetData()
{
return await GetDataAsync();
}
}
Synchronous View project uses a synchronous call to get the data, but due to the constraint of the interface, I need to return a Task, but I am merely interested in the return of the Data thus making the method async.
public class SynchronousViewDatabase : IDatabase
{
public async Task<Data> GetData()
{
return GetData();
}
}
But then it gives warning:
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
Which is sort-of fine with me, since I don't care if it runs synchronously.
Using a Task.Run to suppress the warning seems unnecessary since the call can (and in my case does) originate from a background thread.
Question
Is there a best practice to implement this type of non-await async method? Is it okay to ignore the warning? Is there a better way to implement the async Synchronous call?
Additional
I did convert the interface to a synchronous call, and using the Task.Result in the Asynchronous View (which fixed the warning), but that caused the app to stop responding and just a lot of difficult issues.
Note: I am not stating that using the async keyword magically makes the method run asynchronously.