Combine asyc method into one task

Not sure if this is possible, or if it is already doing something simpler with bound tasks internally, could not handle it from the information I read.

public async Task<ClaimsIdentity> CreateIdentity(string userid )
{
    Guid gid = Guid.Parse(userid);
    Avatar avatar = await _dbContext.Users.Where(d => d.Id == gid).FirstOrDefaultAsync();
    return await CreateIdentity(avatar);
}

public async Task<ClaimsIdentity> CreateIdentity(Avatar avatar)
{
    var identity = new ClaimsIdentity(await GetClaims(avatar)); 
    return identity;
}  
public async Task<List<Claim>> GetClaims(Avatar avatar)
{ 
    var claims = new List<Claim>(); 
    claims = async //(database call to get claims) 
    return claims; 
} 

      

With the above code or any other similar asynchronous code, I'm wondering if there is a way to say continue or continue. So instead of ending up with three tasks, they can be combined so that there is one government computer, or two methods, or even all three?

I'm not sure if this is important, just looking for the right way to do it.

eg. (invalid code I know)

public async Task<ClaimsIdentity> CreateIdentity(string userid )
{
    Guid gid = Guid.Parse(userid);
    Avatar avatar = await _dbContext.Users.Where(d => d.Id == gid).FirstOrDefaultAsync();
    return contiuneinto CreateIdentity(avatar);
}

      

^ to say something like that. so the next method will be in the same task. seems such a waste to create another task for something so small.

+3


source to share


1 answer


Each method async

receives its own state machine and task, you cannot automatically combine them.

You can remove as async

and await

and use Task.ContinueWith

that removes the state machine, but still creates a new problem:

public Task<ClaimsIdentity> CreateIdentity(string userid )
{
    Guid gid = Guid.Parse(userid);
    return _dbContext.Users.Where(d => d.Id == gid).FirstOrDefaultAsync().
        ContinueWith(avatarTask => CreateIdentity(avatarTask.GetAwaiter().GetResult()));
}

      



The easiest way to shorten these tasks and states is to simply combine these methods async

, for example:

public async Task<ClaimsIdentity> CreateIdentity(string userid )
{
    Guid gid = Guid.Parse(userid);
    Avatar avatar = await _dbContext.Users.Where(d => d.Id == gid).FirstOrDefaultAsync();
    var claims = new List<Claim>(); 
    claims = async //(database call to get claims) 
    return new ClaimsIdentity(claims);
}

      

You don't need to worry about it anyway. The cost of creating this task is probably not related to your actual asynchronous operations.

+2


source







All Articles