How to invoke event handler inside an asynchronous callback such that is runs in the calling thread

后端 未结 2 423
夕颜
夕颜 2021-01-24 23:39

I am working on a VS project/solution that is used by different applications. My job is to refactor the project and change it from using xxxAsync method to using BeginInvoke.

相关标签:
2条回答
  • 2021-01-25 00:07

    try to use this, maybe it can help you.

    Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
               //Do something...
            });
    
    0 讨论(0)
  • 2021-01-25 00:32

    As designed, no, you have absolutely no idea which thread is the one on which the client's UI runs.

    You can arbitrarily demand that your InvokeTask() is to be called from that UI thread. Now you know, you can copy SynchronizationContext.Current in the InvokeTask() method and, later, call its Post() or Send() method to call a method that fires the event. This is the pattern used by, for example, BackgroundWorker and async/await. Do note that copying the Current property is required to make this work, don't skip it.

    That of course still won't work when your InvokeTask() method is not called from the UI thread, you'll see that Synchronization.Current is null and have no hope to marshal the call. If that's a concern then you could expose a property of type ISynchronizeInvoke, call it SynchronizingObject. Now it is up to the client code to make the call, they'll have no trouble setting the property, they'll simply assign this in their form class constructor. And you use the property's Post or Send method to call the method that raises the event. This is the pattern used by for example the Process and FileSystemWatcher classes. Don't use it if you expect your library to be used by non-Winforms client apps, unfortunately later GUI libraries like WPF and Silverlight don't implement the interface. Otherwise the exact same problem with approaches like calling Control.Begin/Invoke() yourself.

    0 讨论(0)
提交回复
热议问题