C# 在工作线程中调用主线程中的方法

本文介绍了一种在非UI线程中通过回调委托方法更新主线程的技术方案。该方案适用于需要从后台线程更新GUI的情况,通过创建带有回调功能的线程类实现跨线程的UI更新。

有些调用需要在主线程中去做,如果在控件中,则可以用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]));
           }
            }


        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值