简体   繁体   English

C# 后台工作人员问题

[英]C# Background Worker Question

I have a background worker that does basically the following:我有一个后台工作人员,它基本上执行以下操作:

  1. Find next available file and mark it as in process查找下一个可用文件并将其标记为处理中
  2. Process the file and save the updated version as a new file处理文件并将更新的版本保存为新文件
  3. Mark the original as processed将原件标记为已处理

The above steps will need to loop and continue processing while there are files to process.当有文件要处理时,上述步骤将需要循环并继续处理。

I would like the Background Worker to be able to be stopped, and I see the WorkerSupportsCancellation setting, but how do I ensure that it can only stop between files, not while a file is being processed?我希望后台工作人员能够停止,并且我看到了 WorkerSupportsCancellation 设置,但我如何确保它只能在文件之间停止,而不是在处理文件时停止?

Set WorkerSupportsCancellation to true, and periodically check the CancellationPending property in the DoWork event handler.WorkerSupportsCancellation设置为 true,并定期检查DoWork事件处理程序中的CancellationPending属性。

The CancelAsync method only sets the CancellationPending property. CancelAsync方法仅设置CancellationPending属性。 It doesn't kill the thread;它不会杀死线程; it's up to the worker to respond to the cancellation request.由工人来响应取消请求。

eg:例如:

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

You have to check CancellationPending procepty of background worker at the end of file processing您必须在文件处理结束时检查后台工作人员的 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