试着给后台工作人员计时,如果时间太长就取消

本文关键字:时间 如果 取消 后台 工作人员 | 更新日期: 2024-07-27 10:34:31

我正在解析C#应用程序中的一个网页,我希望能够计算它需要多长时间,如果超过一定时间,则取消它。我研究了两个Timer类,但仍然是一片空白。任何帮助都将不胜感激。

试着给后台工作人员计时,如果时间太长就取消

我希望这能帮助你摆脱

using System;
using System.ComponentModel;
using System.Threading;
namespace ConsoleApplication1
{
    internal class Program
    {
        private static BackgroundWorker worker;
        private static Timer workTimer;
        private static void Main(string[] args)
        {
            Console.WriteLine("Begin work");
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.WorkerSupportsCancellation = true;
            worker.WorkerReportsProgress = true;
            worker.RunWorkerAsync();
            // Initialize timer
            workTimer = new Timer(Tick, null,  
                                  new TimeSpan(0, 0, 0, 10),  // < Amount of time to wait before the first tick.
                                  new TimeSpan(0, 0, 0, 10)); // < Tick every 10 second interval
            Console.ReadLine();

        }
        private static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            workTimer.Dispose();
            if (e.Cancelled) return;
            // Job done before timer ticked
            Console.WriteLine("Job done");
        }
        private static void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 12; i++)
            {
                // Cancel the worker if cancellation is pending.
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
                Console.WriteLine(i);
                Thread.Sleep(1000);                
            }
        }
        private static void Tick(object state)
        {
            // Stop the worker and dispose of the timer.
            Console.WriteLine("Job took too long");
            worker.CancelAsync();
            worker.Dispose();
            workTimer.Dispose();
        }
    }
}

这里有两个问题:

  • 在一定时间后生成取消请求
  • 正在取消分析操作

第一次,你可以使用Timer,正如你所建议的那样(实际上有三个"Timer"类)-最有可能成功的是System.Threading.Timer。它的回调将发生在池线程上,因此即使你的解析操作仍在运行,也应该发生。(在担心实际取消之前,请使用Debug.Print或调试器来完成此操作。)

对于第二部分,你需要有一些方法来告诉你的解析过程放弃——这可以是CancellationToken,也可以是全局变量或WaitEvent——有很多选择,但如果不了解更多解析过程以及你对其代码的访问权限,很难提出最好的选择。

当然,如果您有足够的访问解析代码的权限来添加取消检查,那么您可以只进行if(DateTime.UtcNow > _timeoutAt)测试,在这种情况下,您不需要独立的计时器。。。(如果不明显,您应该在开始解析操作之前设置_timeoutAt = DateTime.UtcNow.AddSeconds(xxx)