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);
...
}
public async static Task<int> GetInstanceIdAsync(IPrincipal user, Entities db)
{
var userManager =
new UserManager<ControliUser>(new UserStore<ControliUser>(db));
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?
source
share