簡體   English   中英

C# 后台工作人員問題

[英]C# Background Worker Question

我有一個后台工作人員,它基本上執行以下操作:

  1. 查找下一個可用文件並將其標記為處理中
  2. 處理文件並將更新的版本保存為新文件
  3. 將原件標記為已處理

當有文件要處理時,上述步驟將需要循環並繼續處理。

我希望后台工作人員能夠停止,並且我看到了 WorkerSupportsCancellation 設置,但我如何確保它只能在文件之間停止,而不是在處理文件時停止?

WorkerSupportsCancellation設置為 true,並定期檢查DoWork事件處理程序中的CancellationPending屬性。

CancelAsync方法僅設置CancellationPending屬性。 它不會殺死線程; 由工人來響應取消請求。

例如:

private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    while( !myBackgroundWorker.CancellationPending )
    {
        // Process another file
    }
}

您必須在文件處理結束時檢查后台工作人員的 CancellationPending procepty

    static void Main(string[] args)
            {
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.WorkerSupportsCancellation = true;
                bw.RunWorkerAsync();
                Thread.Sleep(5000);
                bw.CancelAsync();
                Console.ReadLine();
            }

            static void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                string[] files = new string[] {"", "" };
                foreach (string file in files)
                { 
                    if(((BackgroundWorker)sender).CancellationPending)
                    {
                        e.Cancel = true;
                        //set this code at the end of file processing
                        return;
                    }
                }
            }

暫無
暫無

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

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