【问题标题】:Invoke C# Tasks In Linear Order one after the other一个接一个地以线性顺序调用 C# 任务
【发布时间】:2015-02-24 04:27:50
【问题描述】:

我需要一个接一个地调用多个任务,并且任务的结果应该依赖于另一个才能开始。另外,我们如何从任务方法返回失败的结果?因为我的任务方法有一个逻辑,它什么时候会返回数据,并且基于其他一些条件它应该返回失败的结果,并且基于下一个任务方法不应该执行。

这是我的控制器操作-

        //
        // 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 帖子,但无法在我的场景中使用它-Run sequence of tasks, one after the other

【问题讨论】:

  • 那你为什么用tasks呢?
  • 请比“无法正常工作”更具体。另一篇文章中的答案似乎是相关的;为什么不是你的情况?
  • 我已经为 ASP.Net EF Identity 2.0 实现了简单的自定义用户存储,需要覆盖 IUserStore、IUserPasswordStore 和 IUserSecurityStampStore 接口的 Task 方法
  • @PeterDuniho 问题是我无法更改服务方法标头,因为这些标头需要在实现接口的服务类中定义。因此,某些事情只需要在 Controller-Action 中进行管理,但无法通过,任何指导将不胜感激
  • 无法通过什么?究竟是什么不工作?

标签: c# asp.net-mvc task asp.net-4.5


【解决方案1】:

您可以使用 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++)
            { }
        }
    }

【讨论】:

  • OP 已经表明(以模糊、不透明的方式授予)ContinueWith() 在他的场景中不起作用。请解释尽管如此,您的示例如何为他的问题提供了答案。
猜你喜欢
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 2014-07-09
  • 2018-03-30
  • 1970-01-01
  • 2011-11-21
  • 2019-04-21
  • 2014-07-15
相关资源
最近更新 更多