using System.Threading;
- 运行线程
Thread thread = new Thread(fun);//线程函数,fun不能有参数
或者使用lambda传入函数:new Thread(() => {
Console.WriteLine("xx");
});
thread.IsBackground = true;//前台线程退出则后台线程也退出,如果使用默认的false,则前台线程退出后,程序也不会退出
thread.Start();//开始运行
- 结束线程
thread.Abort();
- 线程名称
获取和设置当前线程的名称
Thread.CurrentThread.Name
- 暂停当前线程
Thread.Sleep(1000);
- 互斥对象
Mutex mutex = new Mutex();
mutex.WaitOne();//调用多次进行多次上锁,需要多次解锁
.........保护代码........
mutex.ReleaseMutex();
- 事件
public ManualResetEvent manualEvent = new ManualResetEvent(false);//true代表终止状态,可以被使用,fasle代表非终止,不可被使用
线程代码(无限循环中,执行一次就暂停,等待信号)
manualEvent.WaitOne();
.................
manualEvent.Reset();
让线程代码运行
manualEvent.Set();
判断线程是否正在运行
manualEvent.WaitOne(0)//返回值为ture代表正在被使用