始于 System.Threading.Thread 类
ThreadStart th1 = new ThreadStart(函数调用A方法);
Thread childThread = new Thread(th1);
.Start(); 开始
.Start("函数调用A方法的参数");
.Abort(); 结束
Thread.Sleep(1000); 暂停ms
Wait 等待
- static void Main(string[] args)
- {
- Thread myThread; //声明线程
- //用线程起始点的ThreadStart委托创建该线程的实例
- myThread = new Thread(new ThreadStart(createThread));
- myThread.Start(); //启动线程
- }
-
- public static void createThread()
- {
- Console.Write("创建线程");
- }
挂起和恢复:
- static void Main(string[] args)
- {
- Thread myThread; //声明线程
- //用线程起始点的ThreadStart委托创建该线程的实例
- myThread = new Thread(new ThreadStart(createThread));
- myThread.Start(); //启动线程
- myThread.Suspend(); //挂起线程
- myThread.Resume(); //恢复挂起的线程
- }
-
- public static void createThread()
- {
- Console.Write("创建线程");
- }
using System.Threading;
- private void btn1_Click(object sender, EventArgs e)
- {
- Thread thread = new Thread(() =>
- {
- for (int i = 1; i < 20; i++)
- {
- Console.WriteLine(i);
- Thread.Sleep(1000);
- }
- });
- thread.IsBackground = true;//设置为后台线程
- thread.Start();
- }
Thread 构造方法原型:
- public Thread(ThreadStart start)
- {
- if (start == null)
- {
- throw new ArgumentNullException("start");
- }
-
- SetStartHelper(start, 0);
- }
ThreadStart 的类型是委托 void (){.....};
- namespace System.Threading
- {
- [ComVisible(true)]
- public delegate void ThreadStart();
- }
构造方法1个参数,参数的类型是委托。
所以 start变量 传进去的必须是一个方法 无名无参 ()=>{ ..... };
thread.IsBackground = true;//设置为后台线程
thread.Start(); // 开始线程
- //通过跨线程给控件赋值
- private void btnExecute1_Click(object sender, EventArgs e)
- {
- Thread thread = new Thread(() =>
- {
- for (int i = 0; i < 10; i++)
- {
- // this.lblResult1.Text = i.ToString();
- if (this.lblResult1.InvokeRequired)
- {
- this.lblResult1.Invoke(
- new Action<string>(data => { this.lblResult1.Text = data; }),
- i.ToString()
- );
-
- Thread.Sleep(300);
- }
- }
- });
- thread.IsBackground = true;
- thread.Start();
- }
这里只要看 this.lblResult1.Invoke( 参数1 , 参数2 ); 这句
- public object Invoke(Delegate method, params object[] args)
- {
- using (new MultithreadSafeCallScope())
- {
- Control control = FindMarshalingControl();
- return control.MarshaledInvoke(this, method, args, synchronous: true);
- }
- }
- // args的值 再传给 method的参数中
注: i.ToString() 再传给 data
与method委托方法匹配的委托是
- namespace System
- {
- [__DynamicallyInvokable]
- public delegate void Action<in T>(T obj);
- }
相当于参数传方法,方法的参数再传参数。