以线性顺序一个接一个地调用C#任务
本文关键字:一个 调用 任务 顺序 线性 | 更新日期: 2024-07-27 05:23:56
我需要一个接一个地调用多个任务,任务的结果应该依赖于另一个任务的开始。此外,我们如何从任务方法返回失败的结果?由于我的任务方法有一个返回数据的逻辑,基于其他条件,它应该返回失败的结果,基于此,下一个任务方法不应该执行。
这是我的控制器操作-
//
// 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);
}
以下是服务方法-
/// <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));
}
我已经审阅了这篇SO文章,但在我的场景中无法做到这一点——运行一系列任务,一个接一个
您可以使用ContinueWith执行任务。这些可以用链条锁住。https://msdn.microsoft.com/en-us/library/dd270696%28v=vs.110%29.aspx.例如:
class Program
{
static void Main(string[] args)
{
Task t1 = new Task(() => TaskOneWork());
Task t2 = t1.ContinueWith((t) => TaskTwoWork());
t1.Start();
t2.Wait();
}
private static void TaskOneWork()
{
for(int i = 0 ; i < 1000000; i++)
{ }
}
private static void TaskTwoWork()
{
for (int i = 0; i < 1000000; i++)
{ }
}
}