Sanchaita Chakraborty
Sanchaita Chakraborty

Reputation: 437

Threading in c#

In my application I have a parent thread. I want to know what will happen to the child thread if I suspend the execution of the parent thread? Will they continue their execution or will they will also get suspended and wait for the parent thread to resume its execution? Please help me.

Upvotes: 1

Views: 345

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503120

Threads don't really have a parent/child relationship - once a thread has been started, it's independent of the thread that created it.

(I'm concerned by your use of the word "suspend" for the parent thread though - suspending a thread is generally a bad idea. In particular, if you mean calling Thread.Suspend you should be aware that that has been deprecated. What do you mean, exactly? If you're trying to coordinate work between threads, there are better ways.)

Sample code, showing four threads doing work, being paused, being resumed, and then the process terminating:

using System;
using System.Threading;

public class A  
{
    static void Main()
    {
        // Start off unpaused
        var sharedEvent = new ManualResetEvent(true);

        for (int i = 0; i < 4; i++)
        {
            string prefix = "Thread " + i;
            Thread t = new Thread(() => DoFakeWork(prefix,
                                                   sharedEvent));
            // Let the process die when Main finished
            t.IsBackground = true;
            t.Start();
        }
        // Let the workers work for a while
        Thread.Sleep(3000);
        Console.WriteLine("Pausing");        
        sharedEvent.Reset();

        Thread.Sleep(3000);       
        Console.WriteLine("Resuming");
        sharedEvent.Set();

        Thread.Sleep(3000);
        Console.WriteLine("Finishing");
    }

    static void DoFakeWork(string prefix, ManualResetEvent mre)
    {
        while (true)
        {
            Console.WriteLine(prefix + " working...");
            Thread.Sleep(500);
            mre.WaitOne();
        }
    }
}

Upvotes: 4

Charbel
Charbel

Reputation: 14697

in brief,if you mean child is the thread started from another thread that you call parent, than no the child threads don't get suspended just because the main thread was suspended. check this example: http://www.codersource.net/microsoft-net/c-basics-tutorials/c-net-tutorial-multithreading.aspx

Upvotes: 0

Stuart
Stuart

Reputation: 66882

Threads don't really have the parent-child relationship in .Net - so suspending a thread will not suspend other threads that happen to have been created by it.

Upvotes: 2

Related Questions