I'm using ASP.Net MVC 5 and am creating a controller to allow a manager to add a user to roles. This is what a non-async version of the controller would look like:
public JsonResult UerRoles(string userid, string[] roles)
{
foreach(var role in roles)
{
if(!UserManager.IsInRole(userid, role))
{
UserManager.AddToRole(userid, role);
}
}
...
}
I want to use the UserManager.IsInRoleAsync and UserManager.AddToRoleAsync methods and would like to run these in parallel and then halt execution of the thread until everything is completed. I've not done asynchronous threading before, but it appears that I could do something like this:
public async Task<JsonResult> UserRoles(string userid, string[] roles)
{
IList<Task<IdentityResult>> tasks = new List<Task<bool>>();
foreach(var role in roles)
{
tasks.Add(UserManager.AddToRoleAsync(userid, role));
}
await Task.WhenAll(tasks);
...
}
However, I somehow need to account for the conditional logic of checking if the user is already in the role -- i.e. UserManager.IsInRoleAsycn(userid, role). I'm not sure how to check for that and conditionally add Users to roles all in parallel and asynchronously.
I've seen the ContinueWith method mentioned and it seems like maybe that somehow applies but I can't figure out how that would be implemented. Something like:
UserManager.IsInRoleAsync(userid, role).ContinueWith(t => if(t.Result) { UserManager.AddToRole(userid, role)} ;);
Is there a way to accomplish this?