C#中可以直接操作Thread对象来操作线程:具体代码实现如下:
class Program
{
//C#多线程操作
#region 1、使用System.Threading.Thread
public const int _Repetitions = 1000;
static void Main(string[] args)
{
ThreadStart thredStart = DoWork;
Thread thread = new Thread(thredStart);
thread.Start();
//操作系统倾向于将时间片调拨给高优先级线程
thread.Priority = ThreadPriority.Highest;
//thread.ThreadState 可以来判断线程的状态
#region 可通过线程join操作来实现同步调用的效果
//告诉操作系统暂停执行当前线程,直到另一个线程终止,先执行thread线程,直到该实例表示的线程结束
// thread.Join();
//指定最多等待多长时间完成,过期不候
// thread.Join(10000);
#endregion
for (int count = 0; count < _Repetitions; count++)
{
Console.Write('-');
}
///这种方式线程会轮流执行,而不是运行完一个再开始执行另外一个
Console.ReadKey();
}
public static void DoWork()
{
for (int count = 0; count < _Repetitions; count++)
{
Console.Write('+');
}
}
#endregion
}
}
C#中为了解决线程频繁创建带来的性能开销,C#提供了线程池的操作方式,开发人员只需要告诉线程池要做什么工作,而不需要告诉线程池怎么干,什么时候干即可。当工作完成后,线程不是终止并被销毁,而是回到池中,从而节省了当更多的工作来临时分配新线程的开销。具体代码如下:
static void Main(string[] args)
{
//优点
//1、线程池操作避免了频繁的创建新线程带来的性能损耗,开发人员只需要告诉线程池要做什么工作
//适用场景
//1、多个任务同时执行,每个任务耗时都不是很久(而不是需要几个小时,几天的任务)
//2、线程池不提供对工作线程的引用,因此不能用来执行与其他线程(主线程)同步的工作
ThreadPool.QueueUserWorkItem(DoWork,'+');
for (int count = 0; count < _Repetitions; count++)
{
Console.Write('-');
}
Thread.Sleep(1000);
Console.ReadKey();
}
private static void DoWork(object state)
{
for (int count = 0; count < _Repetitions; count++)
{
Console.Write(state);
}
}
#endregion