c# UI线程与处理线程的交互

在开发界面的过程中,经常会有将耗时操作放到线程中,同时将处理进度在UI线程显示的要求。有以下几种可以达到这种目的:

1. 使用委托

public partial class MainForm : Form
{
	//定义委托,在线程中使用
	private delegate void SetProgressDelegate(int value, string text);
	private delegate void FinishDelegate();

	public MainForm()
	{
		InitializeComponent();
	}

	private void btnStart_Click(object sender, EventArgs e)
	{
		//开启线程
		new Thread(new ThreadStart(SubThread)).Start();
	}

	//线程函数
	private void SubThread()
	{
		FinishDelegate finish = new FinishDelegate(Finish);
		SetProgressDelegate setProgress = new SetProgressDelegate(SetProgress);
		for(int i = 0; i <= 100; i++)
		{
			//跨线程调用委托
			this.Invoke(setProgress, new object[] { i, string.Format("{0}%", i) });
			Thread.Sleep(100);  //模拟耗时任务
		}
		this.Invoke(finish);
	}

	private void SetProgress(int value, string text)
	{
		this.progressBar.Value = value;
		this.lblProgressText.Text = text;
	}

	private void Finish()
	{
		MessageBox.Show("处理完成!");
	}
}

2. 使用SynchronizationContext

public partial class MainForm : Form
{
	//UI线程的上下文
	private SynchronizationContext mUIThreadSyncContext;

	public MainForm()
	{
		InitializeComponent();

		//初始化
		mUIThreadSyncContext = SynchronizationContext.Current;
	}

	private void btnStart_Click(object sender, EventArgs e)
	{
		//开启线程
		new Thread(new ThreadStart(SubThread)).Start();
	}

	//线程函数
	private void SubThread()
	{
		for(int i = 0; i <= 100; i++)
		{
			//更新UI线程
			mUIThreadSyncContext.Post(new SendOrPostCallback(SetProgress), i);
			Thread.Sleep(100);  //模拟耗时任务
		}
		mUIThreadSyncContext.Post(new SendOrPostCallback(Finish), null);
	}

	private void SetProgress(object state)
	{
		this.progressBar.Value = Convert.ToInt32(state);
		this.lblProgressText.Text = state.ToString() + "%";
	}

	private void Finish(object state)
	{
		MessageBox.Show("处理完成!");
	}
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页