HerpaMoTeH
HerpaMoTeH

Reputation: 364

C# Pause/Kill/Stop/Abort a thread

I know there a lot of questions about this, but neither one of them worked with me. So the problem is that I have a thread that is reading some MODBUS devices and I want to be able to start/stop the reading. When connect is chosen I start the thread and when disconnect is chosen I abort the thread. When I start the aborted thread I receive the following excepton:

System.Threading.ThreadStateException: Thread has already been started. at (wrapper managed-to-native) System.Threading.Thread:Thread_internal (System.Threading.Thread,System.MulticastDelegate) at System.Threading.Thread.Start () [0x00000] in :0 at Vyshka.MainClass.Main (System.String[] args) [0x00096] in /home/Vyshka/Main.cs:53

Upvotes: 0

Views: 2443

Answers (3)

HerpaMoTeH
HerpaMoTeH

Reputation: 364

The best solution for the problem is to NULL-ify the variable and then assign it a new pointer.

Upvotes: 0

James
James

Reputation: 82096

It's generally never a good idea to abort threads, not to mention try to re-start an aborted one - once a thread is aborted there is no recovery from it so what your trying to do won't work. Instead spawn a new thread each time and let the old threads abort in isolation.

Alternatively, put login in your thread that controls reading to/from the MODBUS device so you don't need to abort the thread at all.

Upvotes: 1

usr
usr

Reputation: 171178

Create a new thread. You cannot restart a thread.

Btw, you should (almost) never abort a thread. There's a lot of discussion about that on Stack Overflow which will explain why this makes your program inherently broken.

Upvotes: 1

Related Questions