C# Multithreading — Invoke without a Control

前端 未结 7 1184
闹比i
闹比i 2020-12-13 20:44

I am only somewhat familiar with multi-threading in that I\'ve read about it but have never used it in practice.

I have a project that uses a third party library tha

7条回答
  •  清歌不尽
    2020-12-13 21:07

    If you are using WPF:

    You need a reference to the Dispatcher object which manages the UI thread. Then you can use the Invoke or BeginInvoke method on the dispatcher object to schedule an operation which takes place in the UI thread.

    The simplest way to get the dispatcher is using Application.Current.Dispatcher. This is the dispatcher responsible for the main (and probably the only) UI thread.

    Putting it all together:

    class MyClass
    {
        // Can be called on any thread
        public ReceiveLibraryEvent(RoutedEventArgs e)
        {
            if (Application.Current.CheckAccess())
            {
                this.ReceiveLibraryEventInternal(e);
            }
            else
            {
                Application.Current.Dispatcher.Invoke(
                    new Action(this.ReceiveLibraryEventInternal));
            }
        }
    
        // Must be called on the UI thread
        private ReceiveLibraryEventInternal(RoutedEventArgs e)
        {
             // Handle event
        }
    }
    

提交回复
热议问题