How from one thread to suspend the robot of a child thread. Here I have the code:

currentThread = new Thread(() => PlayMp3FromUrl(url)); currentThread.IsBackground = true; currentThread.Start(); 

And then I need to suspend the running thread, with the possibility of continuing its work in the future. I know that the current stream can be suspended with

 Thread.Sleep(Timeout.Infinite); 

And about the suspension from one thread of another thread found only the outdated methods Thread.Suspend and Thread.Resume.

  • What happens if the child thread is suspended when a lock is held, and the thread that will have to wake it up will request this lock? - PetSerAl 3:51
  • if the thread owns the lock and it is suspended, then the lock will be active. Accordingly, other threads that need this blocking will wait. It is recommended to suspend only yourself. Suspend another thread is not worth it. - KoVadim
  • one
    I know about this problem. But in my case, this should not be at all. - Andriy Goliyad
  • Not very beautiful option, but simple. Your workflow checks for a flag indicating whether it is working or "sleeping." If you sleep, it waits for the longest possible time (Thread.Sleep). After waking up, check the flag again. And the second thread manipulates this flag. - Sergej Loos

1 answer 1

To solve this problem, you can use ManualResetEvent

 using System; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Starting Main()"); Thread t = new Thread(MainThread); t.Start(); Thread.Sleep(2000); StopMainThread(); // You can call this from your button handler. Thread.Sleep(5000); Console.WriteLine("Exiting Main()"); } private static void StopMainThread() { Console.WriteLine("Stopping main thread."); _stopper.Set(); } private static void MainThread() { Console.WriteLine("Starting MainThread()"); for (int i = 1; i <= 1000; i++) { Thread thread = new Thread(new ParameterizedThreadStart(ChildThreadMethod)); thread.Start(i); if (_stopper.WaitOne(80, false)) { Console.WriteLine("MainThread() has been told to stop."); break; } } Console.WriteLine("MainThread() is exiting."); } private static void ChildThreadMethod(object objThreadNumber) { int threadNumber = (int)objThreadNumber; Console.WriteLine("Thread #" + threadNumber + " is starting."); for (int i = 1; ; ++i) { Console.WriteLine("Thread #" + threadNumber + " is on iteration " + i); if (_stopper.WaitOne(500, false)) // Sleep for 500 ms, but wake up immediately { // if _stopper is signalled. break; } } Console.WriteLine("Thread #" + threadNumber + " is exiting."); } private static ManualResetEvent _stopper = new ManualResetEvent(false); } }