a confusing problem relative to C# thread!

S

supermonkey

In my opinion, all subthreads will be terminated when the main thread exit
,but the following program pose a surprise to me~
After "Hello world!" was displayed on the screen, the program will wait
until the "RunMe called" was displayed!

why? is the subthread active though the main thread has exited?

how to explain this problem? Thank you :)


// thread.cs
using System;
using System.Threading;

namespace ConsoleApplication10
{
class ThreadTest
{
public void RunMe()
{
Thread.Sleep(1000);
Console.WriteLine("RunMe called");
}

static void Main()
{
ThreadTest b = new ThreadTest();
//Thread t = new Thread(b.RunMe);

Thread t = new Thread(new ThreadStart(b.RunMe));
t.Start();
Console.WriteLine("Hello world!");
}
}
}
 
S

Stephany Young

The behaviour you are seeing is exactly the way it is designed to work.

In short, if you start a thread then you are responsible for stopping that
thread when it needs to be stopped.

There are exceptions to this rule of thumb and one of them is to make the
thread a background thread and then the behaviour you are expecting will
happen:

t.IsBackground = true;
t.Start();
 
D

Duggi

Hi

A thread waits until all its child threads returns.( unless it is a
background thread).

So make RunMe thread as background thread. sothat main thread (Parent
thread ) will not wait for the background thread.

Thanks
-Srinivas.
 
J

Jon Skeet [C# MVP]

Duggi said:
A thread waits until all its child threads returns.( unless it is a
background thread).

No, it's not quite like that. It's not to do with parent threads at all
- it's just that the *process* won't exit until all the non-background
threads have terminated.

You can create one thread (X) and then make X create several "child"
threads, and X can finish well before any of its children do - it won't
live on waiting for the children.
 
D

Duggi

Hi Jon,

You are right...

Verified with a sample code.

I apologize if I mislead anyone in the loop.

Thanks
-Srinivas.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top