Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF Dispatcher.BeginInvoke and UI/Background Threads
    primarykey
    data
    text
    <p>I think I need some clarifications regarding WPFs <em>Dispatcher.Invoke</em> and <em>Dispatcher.BeginInvoke</em> usage.</p> <p>Suppose I have some long running 'work' code like such that is invoked on the press of a button in a simple WPF application:</p> <pre><code>longWorkTextBox.Text = "Ready For Work!"; Action workAction = delegate { Console.WriteLine("Starting Work Action"); int i = int.MaxValue; while (i &gt; 0) i--; Console.WriteLine("Ending Work Action"); longWorkTextBox.Text = "Work Complete"; }; longWorkTextBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction); </code></pre> <p>This code is locking up my user interface while the <em>workAction</em> is being performed. This is because Dispatcher invokes always run on the UI thread, right?</p> <p>Assuming this, <strong>what is the best practice for configuring my dispatcher to execute the <em>workAction</em> in a separate thread from my UI?</strong> I know I can add a <em>BackgroundWorker</em> to my <em>workAction</em> to prevent my UI from locking as such:</p> <pre><code>longWorkTextBox.Text = "Ready For Work!"; Action workAction = delegate { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate { Console.WriteLine("Starting Slow Work"); int i = int.MaxValue; while (i &gt; 0) i--; Console.WriteLine("Ending Work Action"); }; worker.RunWorkerCompleted += delegate { longWorkTextBox.Text = "Work Complete"; }; worker.RunWorkerAsync(); }; longWorkTextBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction); </code></pre> <p>Is there any more elegant ways of doing this besides using the <em>BackgroundWorker</em>? I've always heard that the <em>BackgroundWorker</em> is quirky, so I am curious to know of some alternatives.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload