nour
nour

Reputation: 163

create an async await function using delegates in C#

I have the following delegates that I need to make them 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:

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?

Upvotes: 0

Views: 172

Answers (1)

Ibram Reda
Ibram Reda

Reputation: 2820

  1. In async Methods you can not use out or ref parameter , read why you can't
  2. asyn Method, return specific Async return types such Task,Task<T>,void,IAsyncEnumerable<T>

your code should look like the following

using System;   // for Func
using System.Threading.Tasks; // Task Namespace


//...

public Func<string, Task<User>> GetUserFromAccessToken;

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

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

Upvotes: 1

Related Questions