C # Background working question

I have a background worker that basically does the following:

  • Find the next available file and mark it as in the process
  • Process the file and save the updated version as a new file
  • Mark the original as processed

The above steps will require a cycle and continue processing while there are files to process.

I want the background worker to be stopped, and I see the WorkerSupportsCancellation parameter, but how can I make sure that it can only stop between files, and not during file processing?

+6
source share
2 answers

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

The CancelAsync method sets only the CancellationPending property. He does not kill the thread; he must respond to the employee with a cancellation request.

eg:.

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

You need to check the unregistration in the background in the "Cancel" application 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; } } } 
+5
source

Source: https://habr.com/ru/post/889966/


All Articles