Get result from async method

后端 未结 2 1124
礼貌的吻别
礼貌的吻别 2020-12-10 13:03

I have this method in my service:

public virtual async Task FindByIdAsync(string userId)
{
    this.ThrowIfDisposed();
    if (userId == null)
           


        
相关标签:
2条回答
  • 2020-12-10 13:30
    • Using this in async methods without special thread-locked object is dangerous
    • If you cannot use await, use a code like following.

      Task<User> task = TaskFindByIdAsync();
      
      task.Wait(); //Blocks thread and waits until task is completed
      
      User resultUser = task.Result;
      
    0 讨论(0)
  • 2020-12-10 13:33

    The best solution is to make the calling method async and then use await, as Bas Brekelmans pointed out.

    When you make a method async, you should change the return type (if it is void, change it to Task; otherwise, change it from T to Task<T>) and add an Async suffix to the method name. If the return type cannot be Task because it's an event handler, then you can use async void instead.

    If the calling method is a constructor, you can use one of these techniques from my blog. It the calling method is a property getter, you can use one of these techniques from my blog.

    0 讨论(0)
提交回复
热议问题