如何引发跨线程事件

4

如何从另一个线程触发 GeocodeAddressEventHandler 事件?

    System.Threading.Thread MapThread;
    WinformMap map ;

    public delegate void GeocodeAddressEventHandler(object sender, EventArgs e);
    public event GeocodeAddressEventHandler GeocodeAddressEvent;

    //How to Raise this Event from another thread??
    public void GeocodeAddress_Raised(object sender, EventArgs e)
    {
        MapLib.GeocodeAddress("12798 1ST ST", "", "", "");
    }

    public bool LoadMap(string restorepoint)
    {
        ////////////////////////Engine Controls////////////////////////////////////////////////////////
        try
        {
            System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;

            //This is to instantiate a winform from a Console (will convert to service shortly) 
            MapThread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
            {
                using (System.ServiceModel.OperationContextScope scope = new System.ServiceModel.OperationContextScope(context))
                {
this.GeocodeAddressEvent += new GeocodeAddressEventHandler(GeocodeAddress_Raised);
                 }
            }));
            MapThread.SetApartmentState(System.Threading.ApartmentState.STA);
            MapThread.Start();
            MapThread.Join();
        }
        catch (Exception ex)
        {
            return false;
        }

        return true; 
    }

事实证明,线程在委托的作用域结束后终止。这可能是一种愚蠢的做法,但我在该作用域中放置了一个while Queue.empty { sleep },使其永远不会终止,然后我从另一个线程启动了LoadMap,以便它阻塞我的WCF服务等待永无止境的队列终止。

2个回答


3

2
请注意,Control.Invoke() 仅在您希望 UI 线程执行该方法时才起作用。 - C.Evenhuis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接