In my WPF application I am loading content using Dispatcher.BeginInvoke
in the constructor. My question is will it block the UI thread?
Or is it better to use Task.Factory.StartNew
and then dispatching things back on UI so that application will load first irrespective of the loading content process time?
Which is better approach and why?
They do two very different things:
Task.Factory.StartNew
schedules a delegate for execution on a
thread pool thread. The current thread continues to run without waiting for a result of this task (async). Typically you would spawn a longer running background task so that the UI is not blocked for too long (not "frozen").
Dispatcher.BeginInvoke
schedules a delegate for execution on the
dispatcher (UI) thread. Typically this is done to update some UI
controls with the results of some operation that was executed on a
background thread. Essentially you are updating the UI here.
To answer you questions directly:
You should not schedule lengthy operations on the Dispatcher thread, typically you only want to update UI controls here. The code in the delegate will be executed on the UI thread, which is blocked for the time of the execution. Just put a Thread.Sleep(10000)
in your current code (that you schedule from the constructor) and you will see the UI will freeze. Use a background task for this - either with a Task
or a background worker (both will use a thread pool thread).
Or is it better to use Task.Factory.StartNew and then dispatching things back on UI so that application will load first irrespective of the loading content process time.
Yes!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With