Search code examples
c#winformsthread-abort

How to use thread.abort()


I am simply trying to abort thread by clicking a button to stop the process if user wanted instead of exiting the application.

This is original code:

 private void Abort_Click(object sender, EventArgs e)
    {
     //   thread1.Abort();
    }

    ///  Runs method 'Copy' in a new thread with passed arguments - on this way we separate it from UI thread otherwise it would freeze
    private void backgroundCopy_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e )
    {

        List<object> genericlist = e.Argument as List<object>;
        Thread thread1 = new Thread(() => Copy(genericlist[0].ToString(), genericlist[1].ToString()));
        thread1.Start();
        thread1.Join(); //Waiting for thread to finish
    }

What I have tried:

I tried Abort() thread from button click event by moving thread field out of method, that way you can get access from your button click event, but it throws many errors:

 object sender;
 System.ComponentModel.DoWorkEventArgs e;
 List<object> genericlist = e.Argument as List<object>;
 Thread thread1 = new Thread(() => Copy(genericlist[0].ToString(), genericlist[1].ToString()));



 private void Abort_Click(object sender, EventArgs e)
 {
     thread1.Abort();
 }

 ///  Runs method 'Copy' in a new thread with passed arguments - on this way we separate it from UI 
  thread otherwise it would freeze
 private void backgroundCopy_DoWork( )
 {


     thread1.Start();
     thread1.Join(); //Waiting for thread to finish
 }

That's what I did but I get error:

under e and genericlist : a field initialize can not reference a non static field, method or property.


Solution

  • In case you have to use threads, try this. Otherwise, try cancelAsync like in this link: https://www.wpf-tutorial.com/misc/cancelling-the-backgroundworker/

         // We will set this true to notify the worker threads return.
                private bool shouldAbort;
        // when hitting submit set:
        shouldAbort = false;
        void MethodThatDoesWork()
            {
                    //we should stop if required
                    if (shouldAbort)
                    {
                        state.Stop();
                    }
                //code
            }
    

    we must be sure that all threads are terminated when the form is closed. so we add these controls.

       private void ItemsCopyer_FormClosing(object sender, FormClosingEventArgs e)
           {
             System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
    
            private void btnAbort_Click(object sender, EventArgs e)
            {
                shouldAbort = true;
                btnAbort.Enabled = false;
            }