文章分类

相关文章

C# Winform异步操作

分类:C#     发布:2018-09-27     来源:本站     浏览:144 次

1.不带参数

private void btnGetSites_Click(object sender, EventArgs e)
{
	var thread = new Thread(Func);
	thread.IsBackground = true;
	thread.Start();
}
private void Func()
{
	UpdateUI(() => { lblStatus.Text = "处理中,请稍候..."; });
	//实现业务逻辑      
	UpdateUI(() => { dgvNotify.DataSource = list; lblStatus.Text = "加载完毕"; });
}
public void UpdateUI(Action action)
{
	if (InvokeRequired)
	{
		Invoke(action);
	}
	else
	{
		action();
	}
}

2.传递参数

private void btnGetSites_Click(object sender, EventArgs e)
{
	var start = new ParameterizedThreadStart(ProcessImageWorkSync);
	var thread = new Thread(start) { IsBackground = true };
	object parameter = from   "|"   to   "|"   type;
	thread.Start(parameter);
}
private void ProcessImageWorkSync(object arg)//参数为自定义封装的对象
{
	string[] arr = arg.ToString().Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
	{
		  ProcessImageWork(arr[0], arr[1], arr[2]);
	}
}
public void UpdateUI(Action action)
{
	if (InvokeRequired)
	{
		Invoke(action);
	}
	else
	{
		action();
	}
}

上一篇:C#程序代码耗时统计

下一篇:ASP.NET 读写Webconfig的AppSetting和ConnectionString