C#异步线程的使用



private void FrmSD_Load(object sender, EventArgs e)
{
	//检查配置文件,数据库连接
	//this.BeginInvoke(new Del_DoCheck(DoCheck)); //会堵塞UI线程
	Thread thread = new Thread(new ThreadStart(DoCheck));
	thread.Start();
}

//检查配置文件,数据库连接
private void DoCheck()
{
	if (!File.Exists(Application.StartupPath + "\\DB.ini"))
	{
		//这里的BeginInvoke不会堵塞当前线程,但不能在UI线程中使用
		this.BeginInvoke(new Del_DoCheck_Msg(ShowMsg), "没有下载数据库连接配置文件,无法进行下载操作!");
		lbtnPrint.Enabled = false; //这样在异步线程中修改UI会导致一些问题
		return;
	}
}

//委托,给异步线程使用,方便异步线程修改主线程的UI
public delegate void Del_DoCheck_Msg(String msg);

//提示对话框
private void ShowMsg(string msg)
{
	MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

猜你喜欢

转载自zheyiw.iteye.com/blog/2085078