您的位置:首页 > 产品设计 > UI/UE

WPF、WinForm(C#)多线程编程并更新界面(UI)

2012-07-30 11:11 561 查看
这几天又开始折腾多线程了,久了不用又忘记了,为防止忘记,特收藏一个精典示例,原文出自论坛,适用于WinForm。但WPF略有不同,特在文中增加一行,已备注。

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();
}
}
}


原文:http://topic.csdn.net/u/20101206/18/2bc62315-2e58-47a9-97be-107710592ab8.html?r=70399587
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: