Wednesday, April 19, 2017

Introduction of Dispatcher

Introduction of Dispatcher

Before start Dispatcher, we need to quick overlook of threading model of WPF.

There is two type of Apartment for handling the Threads
1) STA Single threaded Apartment
2) MTA Multi Threaded Apartment

STA - STA contain only one thread , it can be under stand this way when a Thread create a COM object and set to STA then only this thread can access this COM object.

MTA - MTA contain one or more then one threads, object can get call from and of the Thread.

we will not go on this topic further and come back to the dispatcher.

* WPF App start in STA,
* STA have a message queue
* this message queue Synchronize the message calls.
* and Thread outside the object can not update the object directly.
* So need a method call into the message queue to update the Object into the STA.

So come up for this in WPF we have dispatcher, which own the message queue of STA thread.
when Application start it create a Dispatcher object, Dispatcher is associated with UI thread.
in the simple way , when we are working with the UI thread ,behind the scenes WPF is working with Dispatcher but when we create a new thread and want some UI updation for this new thread then we need dispatcher because only dispatcher can update the UI object.

Method in Dispatcher

There are two impotant methods

  • Invoke
  • BeginInvoke
Invoke : 
Invoke execute the Action or delegate in synchronous, means when start execution it return when finish

        public MainWindow()
        {
            InitializeComponent();
            Task.Factory.StartNew(() =>
            {
                ChangeText();
                this.UpdateLayout();
            });
        }

        private void ChangeText()
        {
            Dispatcher.Invoke(() =>
            {
                txtNameTextBox.Text = "Call By Invoke";
            });           

        }


BeginInvoke : 
Invoke execute the Action or delegate in asynchronous, means when start execution it return immediately.

        public MainWindow()
        {
            InitializeComponent();
            Task.Factory.StartNew(() =>
            {
                ChangeText();
                this.UpdateLayout();
            });
        }

        private void ChangeText()
        {
            Dispatcher.BeginInvoke(() =>
            {
                txtNameTextBox.Text = "Call By BeginInvoke";
            });           

        }



!The COM threading model is called an "apartment" model,