在开发程序的过程中往往使用到线程,直接在线程中操作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;
}