1 以下情况下请使用Thread:
(1)要控制所创建线程的优先级;
(2)希望所使用的线程维护其标识,该标识要与线程一起进行各种操作,经过许多不同的时段;
(3)所使用的线程的寿命较长;
class EntryPoint
{
static int interval;
staticvoid Main()
{
Console.Write("Interval to display resultsat?>");
interval=int.Parse(Console.ReadLine());
Thread thisThread = Thread.CurrentThread;
thisThread.Name="Main Thread";
ThreadStartWorkerStart=new ThreadStart(StartMethod);
workerThread.Name="Worker";
workerThread.Start();
DisplayNumbers();
Console.WriteLine("Main Thread Finished");
Console.ReadLine();
}
Static void StartMethod()
{
DisplayNumbers();
Console.WriteLine("Worker Thread Finished");
}
Static void DisplayNumbers()
{
Thread thisThread=Thread.CurrentThread;
string name=thisThread.Name;
Console.WriteLine("Starting thread:"+name);
Console.WriteLine(name+":CurrentCulture="+thisThread.CurrentCulture);
for(inti=1;i<=8*interval;i++)
{
if(i%interval==0)
Console.WriteLine(Name+":counthas reached"+i);
}
}
}
2 以下情况请使用ThreadPool
(1)要以最简单的方式创建和删除线程;
(2)应用程序使用线程的性能要优先考虑;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Threading;
namespaceConsoleApplication1
{
class Program
{
Console.Write("Interval to display resultsat?>");
interval=int.Parse(Console.ReadLine());
ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod));
Thread.Sleep(100);
ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod));
Console.ReadLine();
}
Static void StartMethod(Object stateInfo)
{
DisplayNumbers("Thread"+DateTime.Now.Millisecond.ToString());
Console.WriteLine("Thread Finished");
}
Static void DisplayNumbers(String GivenThreadName)
{
Console.WriteLine("Starting thread:"+GivenThreadName);
for(inti=1;i<=8*interval;i++)
{
if(i%interval==0)
{
Console.WriteLine("counthas reached"+i);
Thread.Sleep(1000);
}
}
}
}