1. 程式人生 > 其它 >c# 執行緒中訪問UI

c# 執行緒中訪問UI

方式一:

 1         private void btnCalc_Click(object sender, EventArgs e)
 2         {
 3             new Thread(new ThreadStart(Test)).Start();
 4         }
 5 
 6         private void Test()
 7         {
 8             if (this.textBox1.InvokeRequired)
 9             {
10                 this.textBox1.Invoke
(new MethodInvoker(Test)); 11 } 12 else 13 { 14 this.textBox1.Text = "12345"; 15 } 16 }

 

方式二:

        public Form1()
        {
            InitializeComponent(); 
            content = SynchronizationContext.Current;
        }

        
private SynchronizationContext content = null; private void btnCalc_Click(object sender, EventArgs e) { new Thread(new ThreadStart(Test2)).Start(); } private void Test2() { content.Post((e) => { if (this
.textBox1.InvokeRequired) { this.textBox1.Invoke(new MethodInvoker(Test)); } else { this.textBox1.Text = "12345"; } }, null); }