1 以下情况下请使用Thread:
(1)要控制所创建线程的优先级;
(2)希望所使用的线程维护其标识,该标识要与线程一起进行各种操作,经过许多不同的时段;
(3)所使用的线程的寿命较长;
class EntryPoint
{
static int interval;
static void Main()
{
Console.Write("Interval to display results at?>");
interval=int.Parse(Console.ReadLine());
Thread thisThread = Thread.CurrentThread;
thisThread.Name="Main Thread";
ThreadStart WorkerStart=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+":Current Culture="+thisThread.CurrentCulture);
for(int i=1;i<=8*interval;i++)
{
if(i%interval==0)
Console.WriteLine(Name+":count has reached"+i);
}
}
}
2 以下情况请使用ThreadPool
(1)要以最简单的方式创建和删除线程;
(2)应用程序使用线程的性能要优先考虑;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
Console.Write("Interval to display results at?>");
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(int i=1;i<=8*interval;i++)
{
if(i%interval==0)
{
Console.WriteLine("count has reached"+i);
Thread.Sleep(1000);
}
}
}
}