C#利用委派來更新UI

介紹

1.首先建立兩個執行緒

Thread Thread_A;
Thread Thread_B;

2.建立方法判斷物件的執行緒是否在同一執行緒上,如果不同的話就執行委派

(1).利用InvokeRequired判斷物件的執行緒是否在同一執行緒上
(2).利用Invoke進行同步線程的動作

public delegate void Thread_Helper(TextBox Box, string text);
public void Print(TextBox Box, string text)
{
     if (Box.InvokeRequired)
     {
       Thread_Helper helper = new Thread_Helper(Print);
       Box.Invoke(helper, Box, text);
     }
     else
     {
       Box.Text = text;
     }
 }
            

完整程式碼

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.Threading.Tasks;
using System.Windows.Forms;

namespace Thread_Test
{
    public partial class Form1 : Form
    {
        Thread Thread_A;
        Thread Thread_B;
        class Calculate
        {
            public TextBox Output;
            public delegate void Thread_Helper(TextBox Box, string text);
            public void Print(TextBox Box, string text)
            {
                if (Box.InvokeRequired)
                {
                    Thread_Helper helper = new Thread_Helper(Print);
                    Box.Invoke(helper, Box, text);
                }
                else
                {
                    Box.Text = text;
                }
            }
            public void Count()
            {
                for(int i = 0; i <= 100; i++)
                {
                    Print(Output, i.ToString());
                    Thread.Sleep(100);
                }
            }
        }
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Start_Bt_Click(object sender, EventArgs e)
        {
            Calculate Output_A = new Calculate
            {
                Output = Thread_A_Output
            };
            Calculate Output_B = new Calculate
            {
                Output = Thread_B_Output
            };
            Thread_A = new Thread(Output_A.Count);
            Thread_B = new Thread(Output_B.Count);
            Thread_A.Start();
            Thread_B.Start();
        }

        private void Stop_Bt_Click(object sender, EventArgs e)
        {
            Thread_A.Abort();
            Thread_B.Abort();
        }
    }
}

原始碼下載

https://mega.nz/#!nTwzzKoa!ciyo9gyjMZjbEZlZp3wjJwmCOceDc8xfiS43Vb1I2qQ

Last modification:November 17th, 2018 at 01:19 pm