0

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

Buzz
  • 6,030
  • 4
  • 33
  • 47
HerpaMoTeH
  • 364
  • 3
  • 13

3 Answers3

1

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.

usr
  • 168,620
  • 35
  • 240
  • 369
1

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.

James
  • 80,725
  • 18
  • 167
  • 237
0

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

HerpaMoTeH
  • 364
  • 3
  • 13