This might seems like a strange question but a Thread can'r run if the main Thread stops

T

Tony Johansson

Hi!

I just want to make sure that have understood this correct.
If the main thread stop than all other thread will stop and the application
will exit.

So without having a main thread running it's impossible to use any other
threads.

//Tony
 
A

Arne Vajhøj

I just want to make sure that have understood this correct.
If the main thread stop than all other thread will stop and the application
will exit.

So without having a main thread running it's impossible to use any other
threads.

Not true.

Threads can continue to run even with main thread ended.

Exact behavior depends on whether it is a background thread
or not.

Background threads die when no foregrund threads left.

Arne
 
A

Arne Vajhøj

Not true.

Threads can continue to run even with main thread ended.

Exact behavior depends on whether it is a background thread
or not.

Background threads die when no foregrund threads left.

Try these two programs for demo:

using System;
using System.Threading;

namespace E
{
public class Program
{
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(NonBackground));
t.Start();
Console.ReadKey();
}
public static void NonBackground()
{
while(true)
{
Console.WriteLine("I am not in background");
Thread.Sleep(1000);
}
}
}
}

using System;
using System.Threading;

namespace E
{
public class Program
{
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(Background));
t.IsBackground = true;
t.Start();
Console.ReadKey();
}
public static void Background()
{
while(true)
{
Console.WriteLine("I am in background");
Thread.Sleep(1000);
}
}
}
}

Arne
 

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