簡體   English   中英

如何一遍又一遍地啟動和停止后台線程?

[英]How do I start and stop background thread over and over again?

我有具有 UI 和后台線程的 c# 應用程序。 根據用戶輸入,我喜歡停止和啟動后台線程。 正如我所見,我在這里有兩個選擇:

1)完全停止,然后將后台線程作為新線程啟動(我無法做到這一點。我一直收到我的進程結束消息)

2)暫停后台線程,直到用戶再次單擊運行。

這是我在 bw.CancelAsync() 之后再次調用的代碼;

    private void StartBackgroundWorker()
    {
        bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += bw_DoWork;
        bw.RunWorkerCompleted += bw_RunWorkerCompleted;
        bw.RunWorkerAsync("Background Worker");
    }

您不能像那樣啟動和停止后台工作程序,但是在您的 DoWork 事件中,您可以讓它詢問它是應該執行還是等待。

您還可以子類化 BackgroundWorker(覆蓋 OnDoWork() 方法),並向其添加啟動/暫停方法以切換私有等待句柄,這比讓您的 UI 了解 ManualResetEvent 好得多。

//using System.Threading;

//the worker will ask this if it can run
ManualResetEvent wh = new ManualResetEvent(false);

//this holds UI state for the start/stop button
bool canRun = false;

private void StartBackgroundWorker()
{
    bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bw.DoWork += bw_DoWork;
    bw.RunWorkerCompleted += bw_RunWorkerCompleted;
    bw.RunWorkerAsync("Background Worker");
}


void bw_DoWork(object sender, DoWorkEventArgs e)
{
     while(true) 
     {
          //it waits here until someone calls Set() on wh  (via user input)
          // it will pass every time after that after Set is called until Reset() is called
          wh.WaitOne()

         //do your work

     }
}


//background worker can't start until Set() is called on wh
void btnStartStop_Clicked(object sender, EventArgs e)
{
    //toggle the wait handle based on state
    if(canRun)
    {
        wh.Reset();
    }
    else {wh.Set();}

    canRun= !canRun;
    //btnStartStop.Text = canRun ? "Stop" : "Start";
}

您始終可以中止線程並捕獲 ThreadAbortedException。 我不確定這是否是最簡潔的解決方案,因為異常會導致大量開銷,但我認為這比像 Dan 建議的那樣在代碼中傳播 WaitOne 更好。

另一種解決方案是從線程類繼承,並在該類中添加一個停止或暫停線程的函數。 這樣你就可以隱藏實現的細節。

暫無
暫無

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

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