Waheed
Waheed

Reputation: 10216

Use of dispatcher?

I am using the dispatcher in a my function, the function does some work, some work needs the dispatcher and some does't.

For example

this.Dispatcher.BeginInvoke(delegate()
{
    MessageBoxResult result = MessageBox.Show("Are you sure to do this?", MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.OK)
    {
            busyIndicator.Visibility = Visibility.Visible;
            int add = 3 +4;
            string str = "some string";
            this.CallofSomeFunction(arguments);
            this.CallofAnOtherFunction(arguments);
    }
});

In this example the message box needs the dispatcher. The fist called function don't need the dispatch and in side the second the other message box need the dispatcher.

For all this I have placed all the code in a single dispatcher. Is this approach fine??? or should I use the dispatcher where it is needed??

If the end result is placed on UI. Then should I do all the things in dispatcher (getting result + displaying in UI) or should only place displaying the result in UI in dispatcher.

Upvotes: 0

Views: 206

Answers (2)

Haris Hasan
Haris Hasan

Reputation: 30127

Usually it is a good practise to use Dispatcher only for those tasks which are related to UI. If there is something that can be run without UI thread then why keep UI thread busy for this?

If the end result is placed on UI. Then should I do all the things in dispatcher (getting result + displaying in UI) or should only place displaying the result in UI in dispatcher.

It depends. End result is going to be displayed through UI Thread or dispatcher but if the intermediate code can take long then you should move this code to a background thread and finally use dispatcher to update UI

You should always remember the end goal. End goal is to give a better user experience and no freezing UI. If you can do it without background threads then fine but if your business logic takes time it is always good to use background threads

Upvotes: 1

bobbymcr
bobbymcr

Reputation: 24177

In general, you should only use the dispatcher for interacting with UI controls. It is okay in limited situations to do other very quick operations on the UI thread but avoid anything blocking or long-running as this will lead to a very poor user experience (less responsive, frozen UI, etc.).

Upvotes: 1

Related Questions