简体   繁体   English

使用 C# 中的委托创建异步等待 function

[英]create an async await function using delegates in C#

I have the following delegates that I need to make them async await .我有以下委托,我需要让他们async await

My delegate:我的代表:

public delegate bool GetUserFromAccessTokenHandler(string token, out User user);

public GetUserFromAccessTokenHandler GetUserFromAccessToken;

public FunctionalOperations(IUnitOfWork unitOfWork)
{
      GetUserFromAccessToken = new GetUserFromAccessTokenHandler(GetUserFromAccessTokenFunction);
      _unitOfWork = unitOfWork;
}

Now I need to add async to the method GetUserFromAccessTokenFunction but an error occurs:现在我需要将异步添加到方法 GetUserFromAccessTokenFunction 但发生错误:

private async bool GetUserFromAccessTokenFunction (string token, out User user)
{
     var x = await _unitOfWork.User.Get(...);
}

The two errors that I get are:我得到的两个错误是:

  1. The call is ambiguous between the following methods or properties: 'GetUserFromAccessTokenFunction' and 'GetUserFromAccessTokenFunction'

  2. The return type of an async method must be void, Task or Task<T>

How can I fix my delegate declaration to fit my needs?如何修复我的代表声明以满足我的需求?

  1. In async Methods you can not use out or ref parameter, read why you can'tasync方法中,您不能使用outref参数, 请阅读为什么不能使用
  2. asyn Method, return specific Async return types such Task , Task<T> , void , IAsyncEnumerable<T> asyn方法,返回特定的异步返回类型,例如TaskTask<T>voidIAsyncEnumerable<T>

your code should look like the following您的代码应如下所示

using System.Threading.Tasks; // Task Namespace

//...

public delegate Task<User> GetUserFromAccessTokenHandler(string token);

public GetUserFromAccessTokenHandler GetUserFromAccessToken;

public FunctionalOperations(IUnitOfWork unitOfWork)
{
      GetUserFromAccessToken = new GetUserFromAccessTokenHandler(GetUserFromAccessTokenFunction);
      _unitOfWork = unitOfWork;
}

private async Task<User> GetUserFromAccessTokenFunction (string token)
{
     var x = await _unitOfWork.User.Get(...);
     // ...
     return new User(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM