c#多线程防止界面卡死

当我们的界面需要在程序运行中不断更新数据时,当一个textbox的数据需要变化时,为了让程序执行中不出现界面 卡死 的现像,最好的方法就是 多线程 来解决
一个主线程来 创建 界面,使用一个子线程来执行程序并 更新 主界面

这个问题其实也困或了我很久,但是今天终于解决了,而且我发现很多人有这样的问题,所以我分享一个例子方便大家参考吧。
先来看看我的界面

c#多线程防止界面卡死_第1张图片

当我点击开启线程后

c#多线程防止界面卡死_第2张图片

下面是我的代码

namespace 多线程防止界面卡死

{
    public partial class Form1 : Form
    {
        public delegate void UpdateText(string msg);
        public delegate void ErrorText();
        public UpdateText updateText;
        public ErrorText mErrorText;


        public Form1()
        {
            InitializeComponent();
        }


        public void errorText()
        {
            MessageBox.Show("请输入数字");
            textBox1.Text = "";
            textBox1.Focus();
        }


        public void MyUpdateText(string msg)
        {
            textBox2.AppendText(msg + "\r\n");
            textBox2.ScrollToCaret();
        }


        public void ThreadMethodTxt(int n)
        {
            this.BeginInvoke(updateText, "线程开始执行,执行" + n + "次,每一秒执行一次");
            for (int i = 0; i < n; i++)
            {
                this.BeginInvoke(updateText, i.ToString());
                Thread.Sleep(1000);
            }
            this.BeginInvoke(updateText, "线程结束");
        }


        private void button1_Click(object sender, EventArgs e)
        {
            int n = 0;
            Thread thread = new Thread(new ThreadStart(delegate {
                try
                {
                    n = Convert.ToInt32(textBox1.Text.Trim());
                }
                catch (Exception)
                {
                    this.Invoke(mErrorText);
                    return;
                    throw;
                }
                ThreadMethodTxt(n);
            }));
            thread.IsBackground = true;
            thread.Start();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            updateText = new UpdateText(MyUpdateText);
            mErrorText = new ErrorText(errorText);
            this.AcceptButton = button1;
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
        }


    }

}


从代码可以看出,我的做法是使用委托和BeginInvoke方法实现。

你可能感兴趣的:(c#,winfrom)