I need to invoke multiple Tasks one after the other and the result of the task should be dependent for the other to begin. Also how can we return failed result from the task method? As my task method is having a logic when it will return data and based on some other condition it should return failed result and based on that the next task method should not execute.
Here is my controller action-
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FacebookUserID = null,
UserName = model.Email,
Name = model.Name,
Password = model.Password,
LastFailedAttempt = null,
FailedAttempts = 0,
Status = model.Status,
UserType = model.UserType,
SourceType = model.SourceType,
DateCreated = DateTime.Now,
DateModified = null,
DateConfirmed = null,
Email = model.Email
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
user = await _userService.FindByNameAsync(model.Email);
await SignInAsync(user, false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
And below are the service methods-
/// <summary>
/// Checks and Creates the new Application User
/// </summary>
Task IUserStore<T, int>.CreateAsync(T model)
{
Task taskInvoke = Task.Factory.StartNew(() =>
{
var appUser = GetUserByEmail(model.Email);
if (appUser == null)
{
User user = new User();
user.FacebookUserID = model.FacebookUserID;
user.Name = model.Name;
user.Email = model.Email;
user.Password = model.Password;
user.LastFailedAttempt = null;
user.FailedAttempts = 0;
user.Status = model.Status;
user.UserType = model.UserType;
user.SourceType = model.SourceType;
user.DateCreated = DateTime.Now;
user.DateModified = null;
user.DateConfirmed = null;
_uow.UserRepository.Add(user);
_uow.Commit();
return true;
}
else
{
return false;
//what should I return here if the user already exists?
}
});
return taskInvoke;
}
/// <summary>
/// Finds and Returns the Application User by email
/// </summary>
Task<T> IUserStore<T, int>.FindByNameAsync(string email)
{
Task<T> taskInvoke = Task<T>.Factory.StartNew(() =>
{
return (T)GetUserByEmail(email);
});
return taskInvoke;
}
/// <summary>
/// Finds and returns the user by email
/// </summary>
public ApplicationUser GetUserByEmail(string email)
{
return Mapper.DynamicMap<ApplicationUser>(_uow.UserRepository.Get(x => x.Email == email));
}
I had reviewed this SO post but wasn't able to get this working in my scenario- Run sequence of tasks, one after the other