当接口需要异步Task <T>时,如何在没有编译器警告的情况下获取返回变量

时间:2019-10-30 21:54:15

标签: c# async-await

给出以下界面:

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

现在给出以下类别:

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

接口需要Task<string>返回类型。而且由于Mock仅返回一个简单的原始字符串,因此不得不调用Task.Run(() => Guid.NewGuid().ToString())似乎很愚蠢。

但是尝试使用return Task.FromResult(mockToken);会给出:error CS4016: Since this is an async method, the return expression must be of type 'string' rather than 'Task<string>'

使用return mockToken;会生成: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.

所以我一直坚持编译器警告,除非您全力以赴Task.Run,这似乎效率低下,并且在许多操作上花费巨大

0 个答案:

没有答案