Winform 线程 委托 更新 WinForm界面 防止界面卡死

Winform 线程 委托 更新 WinForm界面 防止界面卡死_第1张图片

 

推荐使用这种方法:通用

using System;
using System.Diagnostics;
using System.Windows.Forms;

public static class ControlUpdata
{
    public static T Invoke(T source, Action action) where T : Control
    {
        try
        {
            if (!source.InvokeRequired)
                action(source);
            else
                source.Invoke(new Action (()=> action(source)));

        }
        catch(Exception ex)
        {
            Debug.WriteLine("Invoke错误:{0)" ,ex.Message);
        }

        return source;
    }
}


//调用方式,控件名字,控件属性
//ControlUpdata.Invoke(控件名字, btn => 控件.属性 = 值);
ControlUpdata.Invoke(progressBar1, pb => pb.Value = 88);
ControlUpdata.Invoke(button1, btn => btn.Text = "测试");
ControlUpdata.Invoke(label1, lbl => lbl.Text = "测试");

 

public void ControlUpdate(Control c, string content)
{
    if (c.InvokeRequired)
        c.Invoke((EventHandler)delegate { c.Text = content; });
    else
        c.Text = content;
}

 

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

namespace InterfaceRefresh
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private bool refresh = true;
        private void button1_Click(object sender, EventArgs e)
        {
            int num = 0;
            
            //new Thread(delegate() //开线程刷新 .net 2.0写法
            new Thread( ()=> //开线程刷新 .net 3.5以上写法
            {
                if (refresh)
                {
                    refresh = !refresh;
                    UpdateButton(button1, "关闭刷新");
                }
                else
                {
                    refresh = !refresh;
                    UpdateButton(button1, "开始刷新");
                }
                
                while (!refresh) //用死循环刷新
                {
                    UpdateTextBox(textBox1, "刷新次数:" + num++);
                }
            }) {IsBackground = true}.Start();
        }

        private void UpdateTextBox(TextBox sender, string content)
        {
            this.Invoke((EventHandler)delegate
            {
                sender.AppendText(content + Environment.NewLine); //TextBox的Text赋值
            }));
        }

        private void UpdateButton(Button sender, string content)
        {
             this.Invoke(new Action( ()=>
             {
                 sender.Text = content; //button的Text赋值
             }));
        }
    }
}

你可能感兴趣的:(Winform 线程 委托 更新 WinForm界面 防止界面卡死)