C#執行緒UI更新,SynchronizationContext方法
阿新 • • 發佈:2019-02-16
找了很多C#執行緒更新UI的方法,還是這個最好用。
就像Android的View.Post();方便簡單。using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { SynchronizationContext cuverContext; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { new Thread(new ThreadStart(ThreadFun)).Start(); } public void ThreadFun() { while (true) { cuverContext.Post(new SendOrPostCallback(ThreadSend), null);//第二個引數可以用來傳輸資料 Thread.Sleep(500); } } public void ThreadSend(Object obj) { textBox1.Text += textBox2.Text; } private void Form1_Load(object sender, EventArgs e) { cuverContext = SynchronizationContext.Current; } } }