簡體   English   中英

嘗試安排背景工作人員的時間,如果需要很長時間,則將其取消

[英]Trying to time a backgroundworker and cancel it if it takes to long

我正在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM