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.StartNewschedules a delegate for execution on athread 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.BeginInvokeschedules a delegate for execution on thedispatcher (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 aTaskor a background worker (both will use a thread pool thread).Yes!