2

I'm getting a lot of CS1998 warnings in my application and I'm looking how to resolve them in my case.

For example I have an IDataService interface that has a method signature Task<DataModel> GetData().

Then I have lets say an implementation of RealDataService : IDataService that does some writing/reading of files and since it uses async I/O methods they are called with await and the method signature is changed to async Task<DataModel> GetData().

This is then called from the UI with the var data = await _dataService.GetData();. All is well up to this point.

But then I have a need test my data and I create another implementation of the data interface MockupDataService : IDataService where data is just hardcoded and no async operations are performed. Everything still works as it should, but those pesky CS1998 warnings start to appear when building the application.

There are a lot of solutions to this problem that can be found online:

  • Disabling this type of warning
  • Using the call of await Task.Yeild();
  • Using the Task.From result -> return await Task.FromResult<DataModel>(new DataModel());
  • I think I've seen more, but can't remember them now.

But none of this solutions feel "more right" than other so I would like to know what is the proper way of solving this? I know a lot of people have much deeper knowledge of async programming in C# and will be able to offer some insights/answers on this issue.

Denis Vitez
  • 608
  • 11
  • 32
  • 2
    The method inside the mock service doesn't need to be `async`, remove that modifier and do `return Task.FromResult(new DataModel());` – DavidG Jul 11 '19 at 14:09

2 Answers2

7

Remove the async keyword from the method. Then use return Task.FromResult(...)

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
7

If there's no await, remove the async keyword. async doesn't make a method asynchronous. It's not part of the method signature. It's just syntactic sugar that allows the use of await to await an already executing asynchronous operation without blocking.

In your test method create an already completed task with Task.FromResult and return it as-is:

public Task<DataModel> GetData()
{
    var model=new DataModel();
    //Add some test data
    return Task.FromResult(model);
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236