WPF、WinForm(C#)多线程编程并更新界面(UI)
2013-10-29 17:25
561 查看
这几天又开始折腾多线程了,久了不用又忘记了,为防止忘记,特收藏一个精典示例,原文出自论坛,适用于WinForm。但WPF略有不同,特在文中增加一行,已备注。
[csharp]
view plaincopyprint?
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();
}
}
}
[csharp]
view plaincopyprint?
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();
}
}
}
相关文章推荐
- 【WPF学习】WPF、WinForm(C#)多线程编程并更新界面(UI)/子线程更新主界面方式
- WPF、WinForm(C#)多线程编程并更新界面(UI)
- WPF、WinForm(C#)多线程编程并更新界面(UI)
- WPF、WinForm(C#)多线程编程并更新界面(UI)(转载积累)
- c#中Winform实现多线程异步更新UI(进度及状态信息)
- wpf 多线程 更新UI 界面
- C#中的多线程与UI响应-防界面假死的多线程
- C#用副线程改主线程(UI线程)的控件属性的方法(包括Winform和WPF)
- 拒绝卡顿——在WPF中使用多线程更新UI
- 拒绝卡顿——在WPF中使用多线程更新UI
- 第一个WPF学习例子--多线程、任务和UI线程一起使用、方法重载 c#书籍
- windows UI Design via c#/ window窗口界面编程 (1)
- C# winform编程中多线程操作控件方法
- 【转载】C# Winform 跨线程更新UI控件常用方法总结
- C# Winform 跨线程更新UI控件常用方法汇总
- C# WINFORM 线程中更新UI
- c# 多线程异步更新UI
- 多线程之winform界面的更新
- WPF中UI及时更新,如何在处理长时间工作时,保持界面的持续更新
- BeginInvoke更新界面 UI死掉 WPF