WPF中使用UI线程

在开发程序的过程中往往使用到线程,直接在线程中操作UI程序崩溃,这个时候怎么办呢?这个时候就要使用UI线程了!

UI线程有两种方式:


1.在UI线程中调用其它方法。当我们想进行的操作比较繁琐,代码量比较大的时候就可以在UI线程中调用方法

<pre name="code" class="csharp">public void ErrBox(string strMsg, string strErr)
{
	m_strMsg = strMsg;
	m_strErr = strErr;

	System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
		TimeSpan.FromSeconds(1), new Action(HelpErrBox));

	return;
}




public void HelpErrBox()
{
<span style="white-space:pre">	</span>if (m_strMsg != "")
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>GSMsgBox.MsgBox(m_strMsg + "," + m_strErr);
<span style="white-space:pre">		</span>Logger.WriteLine(m_strMsg + "," + m_strErr);
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>else
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>GSMsgBox.MsgBox(m_strErr);
<span style="white-space:pre">		</span>Logger.WriteLine(m_strErr);
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>return;
}


2.在UI线程直接进行某些操作。相反,当我们的操作比较简单就不必要写一个方法又去调用了:


public void ErrBox(string strMsg, string strErr)
{
	m_strMsg = strMsg;
	m_strErr = strErr;

	System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
		TimeSpan.FromSeconds(1), new Action(()=>{MessageBox.Show("Hello")}));

	return;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值