3

I'm using .Net 3.5 (C#) and I have a class with Start and Stop methods. I'm using BackgroundWorker.DoWork in order to call the Start method from another thread.
I want to be able to send a command from my main thread to that thread (the one running the Start method) and tell it to stop the current method it's running and start running another (i.e. stop running the Start method and start running the Stop method). What is the best way to do that?

Thanks!

menacheb
  • 475
  • 1
  • 6
  • 17
  • You need to define some kind of negotiation protocol from within your Start method and the outside world, Since you're using .NET 3.5, i would suggest simply to use a boolean which can be red by your start method and set by the outside world, than in your start method you can simply check whether the boolean has been set and if so take appropriate action (like shutting down) – Polity Dec 29 '11 at 09:38

2 Answers2

0

When you are ready to switch to another thread. Let the threadstart method return. This is the best way to gracefully end the thread. Once that is done you can spawn another thread.

P.K
  • 18,587
  • 11
  • 45
  • 51
  • What do you mean by "Let the threadstart method return"? I don't want to wait for the running thread to finish. I want it to stop immediately, and to start running another method. – menacheb Dec 29 '11 at 09:42
  • When your thread is running, it is actually running a method (lets call it threadstart method). If it is just running, then let it keep checking a property(accessible from where you want to spawn another thread), if the property is set to false. Do cleanup and just return from that method. It will end your thread. – P.K Dec 29 '11 at 10:26
  • This is an option, but I don't want to intervene in the start method. Do you have some other idea? – menacheb Dec 29 '11 at 12:04
  • I would be interested to see an alternative solution. Polling is a waste of resources and it pollutes the business logic. The best solution would use interrupts (like a micro-controller say) to switch to the cleanup method but at least abstracting away the polling would be nice. – koreus737 Mar 15 '17 at 13:30
0

There's no simple way to do what you want.

It wouldn't be possible to implement "stop what you're doing and start executing this new method" in a way that's guaranteed to be safe and consistent, so there's no such method in the .NET threading framework.

What you need to do depends on how your thread is structured, but the solution is normally to either poll some property, or (better, if it fits the code architecture) trigger an event that signals the thread to exit (or, in your case, start executing the other method instead).

snemarch
  • 4,958
  • 26
  • 38