Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backgroundworker abort

I recently tried to use backgroundworker instead of "classic" threads and I'm realizing that it's causing, at least for me, more problems than solutions. I have a backgroundworker running a synchronous read (in this case from serialPort) and getting blocked around 30 seconds in 1 code line, then cancellationpending isn't the solution. I'm seeing that if the application gets closed at this point (either with the cross button and Application.Exit()) the process keeps zombie forever.

I need a way to force abort or to kill the backgroundworker thread.

like image 364
MazarD Avatar asked Feb 03 '23 11:02

MazarD


2 Answers

I put one together that (i think) does the job. Please let me know if im waaaay off. Here is a simple exaple of how it works.

var backgroundWorker = new BackgroundWorker(){WorkerSupportsCancellation = true};

backgroundWorker.DoWork += (sender, args) =>
         {                 
                 var thisWorker = sender as BackgroundWorker;
                 var _child = new Thread(() =>
                                               {
                                                   //..Do Some Code

                                               });
                 _child .Start();
                 while (_child.IsAlive)
                 {
                     if (thisWorker.CancellationPending)
                     {
                         _child.Abort();
                         args.Cancel = true;
                     }
                     Thread.SpinWait(1);
                 }                 
         };

 backgroundWorker.RunWorkerAsync(parameter);
 //..Do Something...
backgroundWorker.CancelAsync();

Since the background worker is part of the thread pool, we dont want to abort it. But we can run a thread internally which we can allow an abort to occur on. The backgroundWorker then basically runs until either the child thread is complete or we signal to it to kill the process. The background worker thread can then go back into the read pool. Typically I will wrap this up in a helper class and pass through the delegate method that I want the background thread to run passed in as the parameter and run that in the child thread.

Please someone let me know if im banging my head against a wall but it seems to work fine.. But thats the problem with threads isnt it.. the varying results you can get when you run it at different times.

like image 165
Rob Avatar answered Feb 06 '23 02:02

Rob


The process should not become a zombie, since the BackgroundWorker thread is marked as "background" and should end when the UI is closed.

like image 32
uli78 Avatar answered Feb 06 '23 02:02

uli78