It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the
Thread.Start()
method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require.
Example:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TestThread
{
class Program
{
static void Main(string[] args)
{
//Create object of parameterized thread, so that you can pass parameter to any thread
ParameterizedThreadStart pst = new ParameterizedThreadStart(obj.function1);
//Bydefault threads are Foreground Thread
Thread t1 = new Thread(pst);
//Set Thread Name
t1.Name = "Thread1";
//Passs Parameter to thread
t1.Start(true);
//Create object of ThreadStart, it does not have any parameter
ThreadStart ts = new ThreadStart(obj.function2);
Thread t2 = new Thread(ts);
t2.Name = "Thread2";
//Make it Background Thread
t2.IsBackground = true;
//Run the thread
t2.Start();
Console.ReadKey();
}
public void function1(object val)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("This is parameterized function1 by {0} and Value passed is {1} ", Thread.CurrentThread.Name, val);
}
}
public void function2()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("This is function2 by : " + Thread.CurrentThread.Name);
}
}
}
}
0 comments:
Post a Comment