Background worker to abort

So…

Background Worker is crazy, if you want to use a cancel on it. If you have a deep dive into a long running third party library, it is basically useless, because you can’t really use an easy way to abort. You can call .Cancel(), but you can’t implement the canceling logic inside a third party library. So what you can do?

There are many ways, but here’s a very simple one.

Make the whole control abortable, by attaching to the thread it uses, and just create an abort function, to drop the whole thread.

Class:

public class AbortableBackgroundWorker : BackgroundWorker
    {

        private Thread thread;

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            thread = Thread.CurrentThread;
            try
            {
                base.OnDoWork(e);
            }
            catch (ThreadAbortException)
            {
                e.Cancel = true;
                Thread.ResetAbort();
            }
        }

        public void Abort()
        {
            if (thread != null)
            {
                thread.Abort();
                thread = null;
            }
        }
    }

Implementation:

	abortable.Abort();
	abortable.Dispose();

Leave a Reply

Your email address will not be published. Required fields are marked *