C#: 线程Thread的3种使用方式

1.直接看代码

using System;
using System.Threading;
using System.Timers;
using System.Windows.Forms;

namespace WindowsFormsApp13 {
    public partial class Form1 : Form {

        //当前线程的上下文
        static SynchronizationContext synt; //线程切换,异步执行要用到

        public Form1() {
            synt = SynchronizationContext.Current; //不能在申明时初始化
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            //Thread th = new Thread(new ThreadStart(print));
            //th.Start();
            //下面两行代码与上面的两行代码的效果一样,都是不带参数的Start()
            //Thread tthh = new Thread(print);
            //tthh.Start();

            //带参数的Start(),但是只能带一个参数Object
            Thread th = new Thread(new ParameterizedThreadStart(otherPrint));
            th.Start();
            
        }

        private void otherPrint(object obj) {
            //可以用SynchronizationContext做线程间的跳转,但这里为了方便,用另外一种方式
            //不开启线程安全检查,直接进行线程间的操作
            Control.CheckForIllegalCrossThreadCalls = false;
            this.result.Text = obj as String;
            //使用完之后,重新开启线程安全检查
            Control.CheckForIllegalCrossThreadCalls = true;
        }

        private void print() {
            //可以用SynchronizationContext做线程间的跳转,但这里为了方便,用另外一种方式
            //不开启线程安全检查,直接进行线程间的操作
            Control.CheckForIllegalCrossThreadCalls = false;
            this.result.Text = "123";
            //使用完之后,重新开启线程安全检查
            Control.CheckForIllegalCrossThreadCalls = true;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/84939500
今日推荐