有些调用需要在主线程中去做,如果在控件中,则可以用BeginInvoke,但在非控件的类中开工作线程,要在主线程中执行方法,没有BeginInvoke,则可以在创建线程时将UI线程执行作为回调方法传到工作线程中,在工作线程中回调。
private void SendStrategyStatus()
{
if (m_SendOrderStrategyList.Count == 0)
{
SendOrderStrategyList(CallBackClass.OwnerID);
}
if (m_subThreadCheckStrategyStatus == null)
{
ThreadWithCallBack checkStrategyStatus = new ThreadWithCallBack(SendData2DZH);
m_subThreadCheckStrategyStatus = new Thread(new ThreadStart(checkStrategyStatus.CheckSendOrderStrategyStatus));
m_subThreadCheckStrategyStatus.IsBackground = true;
m_subThreadCheckStrategyStatus.Start();
}
}
public delegate string CallBackDelegate(string message);
public class ThreadWithCallBack
{
// 回调委托
private CallBackDelegate m_callback;
// 构造函数
public ThreadWithCallBack(CallBackDelegate callbackDelegate)
{
this.m_callback = callbackDelegate;
}
// 线程方法
public void CheckSendOrderStrategyStatus()
{
//处理逻辑
//回调UI线程方法
if (m_callback != null)
{
m_callback(string.Format(M_SENDSTRATEGYSTATUS, CallBackClass.OwnerID, cachepsv.strategyID, m_SendOrderStrategyList[cachepsv]));
}
}
}