线程基础知识
线程等待
t.Join(); //线程等待,该方法容许我们等待知道线程t完成。当线程t完成后,主程序会继续运行。
检测线程状态
Console.WriteLine(t.ThreadState.ToString()); //获取t线程的状态
前台线程和后台线程
static void Main(string[] args)
{
var sampleForeground = new ThreadSample(10);
var sampleBackground = new ThreadSample(20);
var threadone = new Thread(sampleForeground.CountNumbers);
threadone.Name = "ForegroundThread";
var threadtwo = new Thread(sampleBackground.CountNumbers);
threadtwo.Name = "BackgroundThread";
threadtwo.IsBackground = true;
threadone.Start();
threadtwo.Start();
//threadone线程完成后,程序结束并且后台线程被终结,这是后台线程与前台线程的主要区别:
//进程会等待所有的前台线程完成工作后再结束工作,但是如果只剩下后台线程,则会直接结束工作
// 一个重要注意事项是如果程序定义了一个不会完成的前台线程,主程序并不会正常结束
}
线程优先级
static void Main(string[] args)
{
Console.WriteLine("current thread priority:"+Thread.CurrentThread.Priority);
Console.WriteLine("Running on all cores avaliable");
RunThreads();
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("Running on a single core");
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
RunThreads();
Console.ReadKey();
}
private static void RunThreads()
{
var sample = new ThreadSample();
var threadOne = new Thread(sample.CountNumbers);
threadOne.Name = "ThreadOne";
var threadTwo = new Thread(sample.CountNumbers);
threadTwo.Name = "ThreadTwo";
threadOne.Priority = ThreadPriority.Highest;
threadTwo.Priority = ThreadPriority.Lowest;
threadTwo.Start();
threadOne.Start();
}
class ThreadSample
{
private bool _isStopped = false;
public void Stop()
{
_isStopped = true;
}
public void CountNumbers()
{
long counter = 0;
while (!_isStopped)
{
counter++;
}
Console.WriteLine();
}
}