Search code examples
c#multithreadingwinformsthread-abort

C# - Abort a looping thread


I have threads that displays of data by looping on a certain interval by using Thread.Sleep.

public class myThread{


            public void threadPBAPI()
            {
                for (int i = 0; i < _PBAPI.Length; i++)
                {
                    try
                    {
                        Console.writeLine();
                        Thread.Sleep(_interval * 1000);
                    }
                    catch (NullReferenceException)
                    {

                    }
                }
            }
}

I want to abort stop this activity because, when i press a button a new set of data will load and want to perform this same activity from the start.

I tried doing Thread.Abort(); on a button Click event. but it did not throw the ThreadAbortException.

on doing Thread.Join(); after Thread.Abort(); it throws the ThreadStateException "Thread Has not been started" when the thread is doing the actions its supposed to be doing.


Solution

  • this worked for me:

    set a global boolean flag -

    isThreadAbort = false.
    

    When its true, you can use

    break;
    

    or

    i = _PBAPI.Length