C# 委托的调用解决界面卡死或者更新的问题
先说委托的调用,再说解决界面更新的问题哈
一,委托调用
- 先声明委托及委托变量
delegate void ProcessFlush(int n);
ProcessFlush m_pft = null;
- 声明委托函数
public void RportProcess(int p)
{
someValue = p;
}
3 初始化委托,调用之前
m_pft = new ProcessFlush(RportProcess);
- 调用委托
4.1 WinFrom中
this.Invoke(m_pft,x );
//或者也可用BeginInvoke(m_pft,x);区别是这个异步,上面那个同步
4.2 wpf中
this.Dispatcher.BeginInvoke(m_pft, x);
//或者是这个this.Dispatcher.Invoke(m_pft, x);
4.3 直接调用其实也可以的,就看涉及到界面否。涉及到界面最好用上面的方式。
m_pft(x);
二 ,界面更新
主体思路: 消息响应里面启动一个新的线程, 线程里面调用委托,委托用异步调用(BeginInvoke),线程的IsBackground属性设置为true
直接上代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WinFormUpdateText
{
public partial class FormUpdateTextText : Form
{
public delegate void UpdateText(string text);
UpdateText m_updateText = null;
public FormUpdateTextText()
{
InitializeComponent();
m_updateText = new UpdateText(UpdateTxtMethod);
}
void UpdateTxtMethod(string text)
{
//richTextBox_TextView.Text += text;
richTextBox_TextView.AppendText(text + "\r\n");
richTextBox_TextView.ScrollToCaret();
}
private void button_UpdateText_Click(object sender, EventArgs e)
{
Thread objThread = new Thread(new ThreadStart(delegate
{
ThreaWorkdMethodTxt();
}));
objThread.IsBackground = true;
objThread.Start();
}
private void ThreaWorkdMethodTxt()
{
string strResult = TimeConsuming();
}
private string TimeConsuming()
{
int length = 5;
for (int i = 0; i < length; i++)
{
string strText = "测试字符测试字符";
Thread.Sleep(1000);
strText += i.ToString();
this.BeginInvoke(m_updateText, strText);
}
//throw new NotImplementedException();
return "";
}
}
}
源代码资源地址:源代码UpdateText