简体   繁体   中英

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?

Set WorkerSupportsCancellation to true, and periodically check the CancellationPending property in the DoWork event handler.

The CancelAsync method only sets the CancellationPending property. 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

    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;
                    }
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM