C# 线程
2013-11-18 11:14
155 查看
线程的方法和状态
Thread类常用方法:Start();启动线程
Sleep(int);静态方法,暂停当前线程指定ms数
Abort();通常使用该方法来终止一个线程
Suspend();该方法并不终止未完成的线程,它仅仅挂起线程,以后可以恢复
Resume();恢复被Suspend()方法挂起的线程执行
新建线程
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Thread { class Program { static void Main(string[] args) { Console.WriteLine("主进程开始"); //声明一个新的线程,可以叫辅助线程 System.Threading.Thread newthread = new System.Threading.Thread(PrintMethod); //启动线程,并传递委托所需要的参数 newthread.Start("我是新线程哦!"); } public static void PrintMethod(object msg) { Console.WriteLine(msg); } } }
龟兔赛跑例子
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadTest { class Program { static void Main(string[] args) { Console.WriteLine("老龟我(主线程)开始跑"); //声明一个新的线程,可以叫辅助线程 Thread newthread = new System.Threading.Thread(Gotobed); //启动线程,并传递委托所需要的参数 newthread.Start("兔哥哥"); for (int i = 0; i < 10; i++) { Console.WriteLine("老龟我继续跑!继续跑!再跑!"); Thread.Sleep(100); } Console.WriteLine("终于到终点了,2B兔子还没到,木哈哈!!!~~"); } public static void Gotobed(object date) { Console.WriteLine("那家伙跑的太慢了,"+date.ToString()+"我睡会儿觉先"); for (int i = 0; i < 15; i++) { Console.WriteLine("小兔子。。ZZZ。。。ZZZ"); Thread.Sleep(100); } Console.WriteLine("都睡了1500年了,那家伙还没来,啊???你怎么在我前面?"); } } }
进程的状态ThreadState
Aborted;线程已经停止AbortRequested;线程Abort方法已经被调用,但是线程还未停止;
Background;线程在后台执行,与属性Thread.IsBackground有关;
Running;线程正在正常运行
Stopped;线程已经倍停止
StopRequested;线程正在倍要求停止
Suspended;线程已经倍挂起
SuspendRequested;线程正在要求倍挂起,但是未来得及响应
Unstarted;未调用Start开始进程
WaitSleepJoin;线程因为调用了Wait(),Sleep(),Join()等方法处于封锁状态
代码获取线程信息
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadTest { class Program { static void Main(string[] args) { Thread t = Thread.CurrentThread; if (t.Name == null || t.Name == "") t.Name = "主线程"; string info = string.Format( "当前线程信息如下\n线程名:{0},\n优先级:{1},\n标识符:{2},\n状态{3},\n是否为后台线程{4},\n是否托管与线程池{5}" ,t.Name,t.Priority,t.ManagedThreadId,t.IsAlive,t.IsBackground,t.IsThreadPoolThread ); Console.WriteLine(info); Thread newt1 = new Thread(PrintCurrentInfo); newt1.Start(newt1); } public static void PrintCurrentInfo(object newt1) { Thread t = (Thread)newt1; t.Name = "新线程"; string info = string.Format( "当前线程信息如下\n线程名:{0},\n优先级:{1},\n标识符:{2},\n状态{3},\n是否为后台线程{4},\n是否托管与线程池{5}" , t.Name, t.Priority, t.ManagedThreadId, t.IsAlive, t.IsBackground, t.IsThreadPoolThread ); Console.WriteLine(info); } } }
相关文章推荐
- C# 线程的暂停和恢复的 实现
- C# 多线程同步和线程通信
- [C#] Parallel.For的线程数
- C#线程系列(5):同步技术之Monitor
- C#线程系列讲座(4):同步与死锁
- C#线程锁(上)
- C#后台线程和UI的交互
- c#中子线程控制进度条的一个简单例子
- c#之线程随机
- [转]C#线程调用带参数的方法
- C#线程类Thread初步
- C#跨线程访问
- [C#]获得线程池中活动的线程数
- C#定时检查子线程是否执行完成(定时器检查)
- 黄聪:C# 使用线程你可能不知道的问题
- C#通过接口与线程通信(捕获线程状态)介绍
- C# 线程手册 第一章 线程定义 线程
- c#跨线程调用控件、函数的问题
- C#中的线程入门
- C# 温故而知新: 线程篇(二)