C#: How to force “calling” a method from the main thread by signaling in some way from another thread

前端 未结 3 595
情深已故
情深已故 2020-12-21 16:26

Sorry for long title, I don\'t know even the way on how to express the question

I\'m using a library which run a callback from a different context from the main thre

3条回答
  •  萌比男神i
    2020-12-21 17:01

    Before you call the 3rd party function, get a reference to Dispatcher.CurrentDispatcher. In the callback function, use dispatcher.Invoke.

    What you end up with will look something like this:

    class MyClass
    {
        private Dispatcher dispatcher;
        public void runThirdParty()
        {
            this.dispatcher = Dispatcher.CurrentDispatcher;
            callThirdPartyFunction(myCallBack);
        }
    
        public void myCallBack()
        {
            this.dispatcher.Invoke(new Action(() =>
            {
                //code to run here.
            }));
        }
     }
    

提交回复
热议问题