-1

Given the following interface:

    public interface IIdentityService
    {
        Task<string> GetToken();
    }

And now given the following class:

    public class MockIdentityService : IIdentityService
    {
        public async Task<string> GetToken()
        {
            string mockToken = Guid.NewGuid().ToString();
            return mockToken;
        }
    }

The interface requires the Task<string> return type. And Since the Mock just returns a simple primitive string, seems silly to have to call Task.Run(() => Guid.NewGuid().ToString()).

However attempt to use return Task.FromResult(mockToken); gives: error CS4016: Since this is an async method, the return expression must be of type 'string' rather than 'Task<string>'

Using return mockToken; generates: warning CS1998: 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.

So I'm stuck with the compiler warning, unless you go full steam Task.Run which seems inefficient, and costly over lots of operations

enorl76
  • 2,562
  • 1
  • 25
  • 38

0 Answers0