簡體   English   中英

限制計時器線程執行時間

[英]Limit timer thread execution time

如何限制計時器線程的執行時間? 我的計時器工作時間很長,應該不超過30秒。

唯一的方法是擁有第二個線程(可能是創建工作線程的那個線程)監視器,然后將其殺死或正常調用以立即退出。 您應該避免殺死線程,並且只能將其用作最后的手段。 這是示例示例:

        Thread t = new Thread(myLongThreadProc);
        t.Start();
        Thread.Sleep(30000);
        t.Abort();

通過“優雅地調用它退出”,我的意思是將一些stop變量設置為某個值,並給線程一些短時間退出自身,否則您將其殺死。 但是要真正退出它是線程函數的設計。 這是示例代碼:

        Thread t = new Thread(myLongThreadProc);
        threadRun = true;
        t.Start();
        Thread.Sleep(30000);
        threadRun = false; //this variable is monitored by thread
        if (!t.Join(1000))  //inside your thread, make sure it does quit in one second
        {                   //when this variable is set to false
            t.Abort();
        }

而且我應該提一下,您的調用方線程不必休眠30秒,但是您可以改用計時器(如果它是表單線程)或做一些有用的事情並定期檢查-或讓第三個工作線程僅計數30秒...

只是讓您的worker方法啟動一個30秒的計時器,並檢查它在您的工作過程中是否已經過去:

    bool timerElapsed;

    public void DoWork()
    {
        timerElapsed=false;
        System.Timers.Timer timer = new System.Timers.Timer(30000);
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        timer.Start();

        while (true)
        {
            if (timerElapsed)
            {
                // handle 30-sec elasped error
                break;
            }
            // continue doing work and break when done
        }
        timer.Stop();
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timerElapsed = true;
    }

暫無
暫無

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

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