当我们的界面需要在程序运行中不断更新数据时,当一个textbox的数据需要变化时,为了让程序执行中不出现界面卡死的现像,最好的方法就是多线程来解决
一个主线程来创建界面,使用一个子线程来执行程序并更新主界面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//创建一个委托,是为访问TextBox控件服务的。
public delegate void UpdateTxt(string msg);
//定义一个委托变量
public UpdateTxt updateTxt;
//修改TextBox值的方法。
public void UpdateTxtMethod(string msg)
{
richTextBox1.AppendText(msg + "\r\n");
richTextBox1.ScrollToCaret();
}
//此为在非创建线程中的调用方法,其实是使用TextBox的Invoke方法。
public void ThreadMethodTxt(int n)
{
this.BeginInvoke(updateTxt, "线程开始执行,执行" + n + "次,每一秒执行一次");
for (int i = 0; i < n; i++)
{
this.BeginInvoke(updateTxt, i.ToString());
//一秒 执行一次
Thread.Sleep(1000);
}
this.BeginInvoke(updateTxt, "线程结束");
}
//开启线程
private void button1_Click(object sender, EventArgs e)
{
Thread objThread = new Thread(new ThreadStart(delegate
{
ThreadMethodTxt(Convert.ToInt32(textBox1.Text.Trim()));
}));
objThread.Start();
}
private void Form1_Load_1(object sender, EventArgs e)
{
//实例化委托
updateTxt = new UpdateTxt(UpdateTxtMethod);
}
}
}
本文介绍了一种在Windows Forms应用程序中使用多线程更新UI的技术。通过将数据更新任务分配给子线程,可以避免界面卡顿,确保程序响应迅速。文章详细展示了如何创建委托以安全地更新界面元素,并提供了完整的示例代码。
391

被折叠的 条评论
为什么被折叠?



