Async nested methods and Asp.Net thread pool

I create asyncWeb Api and after reading some articles about async/ awaitI think that I am doing something wrong.

this is my actual code:

public async Task<IHttpActionResult> GetAccount(int id)
{
    var i = await GetInstanceIdAsync(User, _db); //grabs a thread
    ...
}

public async static Task<int> GetInstanceIdAsync(IPrincipal user, Entities db)
{
    var userManager = 
         new UserManager<ControliUser>(new UserStore<ControliUser>(db));
    //next line grabs another thread but since it was called from an await
    //it holds 2 threads, am I correct?
    var u = await userManager.FindByNameAsync(user.Identity.Name);
    return u == null ? 0 : u.InstanceId ?? 0;
}

So my first question is: is it consuming 2 threads?

If the answer is yes, I made this extension method to prevent this.

public static Task<int?> InstanceIdAsync(this Entities db, IPrincipal user)
{
    var userManager = new UserManager<ControliUser>(new UserStore<ControliUser>(db));
    return userManager.FindByNameAsync(user.Identity.Name).ContinueWith(t =>
    {
        if (t.IsCompleted && t.Result != null)
            return t.Result.InstanceId;
        return null;
    });
}

I think this method will consume only one thread and reduce overhead since it saves the method async

Am I right?

+4
source share
1 answer

So my first question is: is there a consumption of 2 threads?

. async- . , , async . , FindByNameAsync, , . ( await) , .

, 1

, WebAPI. , . , , , - , .

, async -, , , state-machine, ( await).

+3

Source: https://habr.com/ru/post/1608828/


All Articles