在上一遍文章中讲到多线程基础,在此篇文章中咱们来学习C#里面Thread类。Thread类是在.net framework1.0版本中推出的API。若是对线程的概念还不太清楚的小伙伴请阅读个人上一遍文章:多线程系列(一),多线程基础html
在本篇文章中新开启一个线程来异步调用的方法代码为:多线程
private void DoSomeThing(string btnName) { Console.WriteLine($"{btnName} 开始,当前线程id:{Thread.CurrentThread.ManagedThreadId}"); long lResult = 0; for (long i = 0; i < 1_00_000_000; i++) { lResult += i; } Console.WriteLine($"{btnName} 结束,当前线程id:{Thread.CurrentThread.ManagedThreadId}"); }
方式一:基于委托ParameterizedThreadStart异步
ParameterizedThreadStart method = o => this.DoSomeThing("btnThread_Click"); Thread thread = new Thread(method); thread.Start();//开启线程,执行委托的内容
方式二:基于委托ThreadStart函数
ThreadStart method = () => { Thread.Sleep(3000); this.DoSomeThing("btnThread_Click"); }; Thread thread = new Thread(method); thread.Start();//开启线程,执行委托的内容
thread.Suspend();//暂停,挂起线程,若是线程已经挂起,则不起做用学习
thread.Resume();//继续已经挂起的线程测试
thread.Abort();//终止线程,会在当前线程中抛出一个异常引起线程中止,不过会有延迟,由于线程属于计算机资源,程序想停下线程,只能向操做系统通知(抛异常),不必定真的能停下来this
Thread.ResetAbort();//终止当前线程,取消当前线程的全部请求,只能终止一次spa
Thread.Sleep();//使当前线程休眠多少毫秒再继续执行操作系统
方式一:经过thread.ThreadState获取当前线程的状态.net
while (thread.ThreadState != System.Threading.ThreadState.Stopped) { Thread.Sleep(500); Console.WriteLine($"线程_{ thread.ManagedThreadId.ToString("00")}_正在运行中..."); }
方式二:经过Join等待
thread.Join(); //等待线程thread执行完毕
thread.Join(5000); //限时等待,最多等待5000毫秒
thread.Priority = ThreadPriority.Highest;
设置线程的优先级为最高优先级:优先执行,但不表明优先完成,甚至说极端状况下,还有意外发生,不能经过这个来控制线程的执行前后顺序
thread.IsBackground = false;//默认是false 前台线程,进程关闭,线程须要计算完后才退出
thread.IsBackground = true; //关闭进程,线程退出
咱们但愿某个线程在执行某个动做以后触发另外一个动做,下面是我基于Thread封装的线程回调函数
/// <summary> /// 基于thread封装一个回调,启动子线程执行动做A--不阻塞--A执行完后子线程会执行动做B,不阻塞 /// </summary> /// <param name="method">动做A</param> /// <param name="action">动做B</param> private void ThreadWithCallBack(ThreadStart method,Action action) { ThreadStart threadStart = () => { method.Invoke(); action.Invoke(); }; new Thread(threadStart).Start(); }
调用测试代码:
ThreadStart method = () => { this.DoSomeThing("btnThread_Click"); }; Action actionCallBack = () => { Console.WriteLine("method 的回调"); }; this.ThreadWithCallBack(method, actionCallBack);
下面是我基于Thread封装的获取子线程的返回值函数
T t = default(T); ThreadStart threadStart = () => { t = func.Invoke(); }; Thread thread = new Thread(threadStart); thread.Start(); return new Func<T>(() => { thread.Join(); return t; });
调用测试代码
Func<int> func = () => { return DateTime.Now.Hour; }; Func<int> funcThread = this.ThreadWithReturn<int>(func);//非阻塞 int res = funcThread.Invoke();//阻塞
在下一篇中,会继续讲到线程池