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 test
{
public partial class Form1 : Form
{
private delegate void MyUpdate(string str);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.IsBackground = true;
t.Start();
}
void ThreadProc()
{
for (int i = 0; i < 10; i++)
{
Runtime_UpdateUI(i.ToString());
Thread.Sleep(1000);
}
}
private void Runtime_UpdateUI(string str)
{
if (this.InvokeRequired)
{
MyUpdate update = new MyUpdate(Runtime_UpdateUI);
this.Invoke(update, new object[] { str });
}
else
{
label1.Text = str;
}
}
}
}
本文介绍了一个使用C#实现的简单示例,演示了如何在后台线程中更新Windows Forms应用程序的用户界面(UI)。通过创建委托并在需要时调用Invoke方法,可以安全地更新UI元素,避免跨线程访问引发的异常。
1498

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



