关于c#中多线程更新主界面的问题。
实例学习参考。。。。。
经常忘记!!!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace doWorker
{
public partial class Form1 : Form
{
delegate void MyDelegate(int value);
Thread t;
int i = 0;
public Form1()
{
InitializeComponent();
}
// 在新的线程中做“需要长时间做的”工作
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(doWork);
t.Start();
}
// 要长时间做的工作
void doWork()
{
MyDelegate d = new MyDelegate(setValue);
while (true)
{
++i;
//---WinForm--
this.Invoke(d, i);
//----WPF---added by wonsoft.cn---
this.Dispatcher.Invoke(d, i);
Thread.Sleep(100);
}
}
// 更新用户界面
void setValue(int value)
{
label1.Text = value.ToString();
}
// 终止线程的执行
private void button2_Click(object sender, EventArgs e)
{
t.Abort();
}
}
}

本文深入探讨了C#中多线程环境下更新主界面的技术要点,通过实例学习如何在新线程中执行耗时操作,并在主线程中安全地更新UI元素,避免应用程序冻结。
215

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



