-1

I have a thread in my application named "FirstThread" which is running in the background. While trying to stop this running thread using "FirstThread.Abort() " it returns an exception.Can you suggest any solutions for this

 if (FirstThread.ThreadState == System.Threading.ThreadState.Running)
     FirstThread.Abort();

enter image description here

René Vogt
  • 43,056
  • 14
  • 77
  • 99
Antu Philip
  • 33
  • 1
  • 8
  • 3
    `Thread.Abort()` is evil and should **never** be used. https://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation – spender Oct 04 '18 at 12:21
  • ok.Then How can I stop the thread – Antu Philip Oct 04 '18 at 12:22
  • 1
    Welcome to stack overflow. We're going to struggle if you don't specify what the exception is. Additionally a piece of code to demonstrate what is going on would be very helpful. – DubDub Oct 04 '18 at 12:23
  • 1
    Would this be a **ThreadAbortException** by any chance? That's how `Thread.Abort()` works - and is also one of the reasons why it's not at all recommended. – Matthew Watson Oct 04 '18 at 12:24
  • 1
    `Then How can I stop the thread ` Read the link that @Spender provided; it's very useful, athough a bit old. Better nowadays to use [`Task` and task cancellation](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation). – Matthew Watson Oct 04 '18 at 12:30
  • Please take the time to read the [tour] and [ask]. Please don't post exceptions as images (and you posted the most irrelevant part of the stack trace). Please show the _relevant_ code, the exception _type_, _message_ and stack trace. – René Vogt Oct 04 '18 at 12:30
  • Aborting threads can leave the run-time in a corrupted state. You can't trust your program to run correctly after aborting threads. You should only do so if you are trying to forcibly exit your app. – Enigmativity Oct 04 '18 at 12:34
  • Check this [relevant question](https://stackoverflow.com/q/3632149/1997232). – Sinatr Oct 04 '18 at 12:35

1 Answers1

-1

Usually to avoid these exceptions I use flags. You can create a flag called stopFirstThread and rather than abort the thread you set flag value to True, and inside first thread keep checking for this flag, when it become True you can end thread peacefully.

Ebraheem
  • 603
  • 6
  • 24