代码之家  ›  专栏  ›  技术社区  ›  CrazyCoder

使用任务时的执行流。在c等着#

  •  0
  • CrazyCoder  · 技术社区  · 7 年前

    我有一个如下的示例代码,它有逻辑可以在30分钟后取消任务。
    Method1调用Method2和Method3,分别需要15分钟和10分钟才能完成。我已经给出了5分钟的缓冲,并将所有执行的超时限制设置为30分钟。

    public class Program
    {
        static void Main()
        {
            Program p = new Program();
            var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(0.5));
            var token = tokenSource.Token;
            var task = Task.Factory.StartNew(() => {
                p.Method1(token);
            }, token);
    
            try
            {
                task.Wait();
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Method1 did not finish within 1 mins :" + DateTime.Now);
            }
            finally
            {
                tokenSource.Dispose();
            }
            Console.ReadLine();
        }
        public bool Method1(CancellationToken token)
        {
            Console.WriteLine("Inside Method1 :" + DateTime.Now);
            Method2(token);
            return true;
        }
        public bool Method2(CancellationToken token)
        {
            try
            {
                token.ThrowIfCancellationRequested();
    
                Console.WriteLine("Inside Method2 begin :" + DateTime.Now);
                Thread.Sleep(60000); // In the actual code , this line is replaced with the line which executes for more than 1 min.To replicate it, I just made the Thread to sleep.
                if (token.IsCancellationRequested)
                {
                    token.ThrowIfCancellationRequested();
                }
                Console.WriteLine("Inside Method2 end :" + DateTime.Now);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in Method2");
                return false;
    
            }
        }
    }
    

    现在我面临的问题是,方法执行的顺序不同于我在整体执行时间超过30分钟时的示例。假设方法2的执行需要更多的时间来完成。
    期望值:

    内部方法1
    内部方法2
    方法2中的例外
    方法1没有在30分钟内完成

    现实:

    内部方法1
    内部方法2
    方法2中的例外

    需要进行哪些更改才能使执行流程符合预期。有可能吗?

    在这个示例中,我只给出了方法2的示例。实际上,有3-4种方法可以执行一些典型的操作。其中任何一个都可能需要时间来执行。因此,只为Method2设置超时并不能解决问题。

    编辑2

    我已经删除了旧代码,并替换为答案中建议的代码,以避免任何混淆。这里我所做的是让线程睡眠1分钟,因为超时时间只有30秒。这里发生的事情是,当执行到达线程时。睡眠时,它会等待60秒,然后抛出异常。我希望它在30秒结束后立即抛出异常。

    0 回复  |  直到 7 年前
        1
  •  0
  •   nlawalker    7 年前

    密码 Method2 即使在超时触发后仍继续执行-没有任何东西会自动停止它或导致它引发异常。你想做的事叫做 取消 :你想要超时来激活一个信号 方法2 可以偶尔检查,以便在超时触发时结束正在执行的操作或引发异常。

    而不是给 Wait ,创建基于超时的 CancellationTokenSource 具有 new CancellationTokenSource(TimeSpan.FromMinutes(30)) 并将其标记向下传递到任务中运行的所有方法中。然后,这些方法可以将令牌传递到任何 async 方法调用和/或使用令牌上的方法/属性来查看是否触发了超时。看见 here .