C#: 執行緒Thread的3種使用方式
阿新 • • 發佈:2018-12-11
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; } } }