If my interface must return Task what is the best way to have a no-operation implementation?

后端 未结 9 1048
-上瘾入骨i
-上瘾入骨i 2020-11-28 17:59

In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument\'s sake can\'t be changed). If LazyBar

相关标签:
9条回答
  • 2020-11-28 18:27

    Task.Delay(0) as in the accepted answer was a good approach, as it is a cached copy of a completed Task.

    As of 4.6 there's now Task.CompletedTask which is more explicit in its purpose, but not only does Task.Delay(0) still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask.

    The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0) was better than the accepted answer.

    0 讨论(0)
  • 2020-11-28 18:30

    Recently encountered this and kept getting warnings/errors about the method being void.

    We're in the business of placating the compiler and this clears it up:

        public async Task MyVoidAsyncMethod()
        {
            await Task.CompletedTask;
        }
    

    This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.

    0 讨论(0)
  • 2020-11-28 18:37

    If you are using generics, all answer will give us compile error. You can use return default(T);. Sample below to explain further.

    public async Task<T> GetItemAsync<T>(string id)
                {
                    try
                    {
                        var response = await this._container.ReadItemAsync<T>(id, new PartitionKey(id));
                        return response.Resource;
                    }
                    catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
    
                        return default(T);
                    }
    
                }
    
    0 讨论(0)
提交回复
热议问题