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

后端 未结 9 1047
-上瘾入骨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:14

    Today, I would recommend using Task.CompletedTask to accomplish this.


    Pre .net 4.6:

    Using Task.FromResult(0) or Task.FromResult<object>(null) will incur less overhead than creating a Task with a no-op expression. When creating a Task with a result pre-determined, there is no scheduling overhead involved.

    0 讨论(0)
  • 2020-11-28 18:15
    return Task.CompletedTask; // this will make the compiler happy
    
    0 讨论(0)
  • 2020-11-28 18:19

    To add to Reed Copsey's answer about using Task.FromResult, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:

    public static class TaskExtensions
    {
        public static readonly Task CompletedTask = Task.FromResult(false);
    }
    

    With TaskExtensions.CompletedTask you can use the same instance throughout the entire app domain.


    The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask static property

    Task completedTask = Task.CompletedTask;
    
    0 讨论(0)
  • 2020-11-28 18:22

    When you must return specified type:

    Task.FromResult<MyClass>(null);
    
    0 讨论(0)
  • 2020-11-28 18:24

    I prefer the Task completedTask = Task.CompletedTask; solution of .Net 4.6, but another approach is to mark the method async and return void:

        public async Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
        }
    

    You'll get a warning (CS1998 - Async function without await expression), but this is safe to ignore in this context.

    0 讨论(0)
  • 2020-11-28 18:25
    return await Task.FromResult(new MyClass());
    
    0 讨论(0)
提交回复
热议问题