Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>IMO answers stating that you should launch a thread to handle this are misguided. What you need is to jump the window back to the main dispatcher thread.</p> <h3>In WPF</h3> <pre><code>public ShellViewModel( [NotNull] IWindowManager windows, [NotNull] IWindsorContainer container) { if (windows == null) throw new ArgumentNullException("windows"); if (container == null) throw new ArgumentNullException("container"); _windows = windows; _container = container; UIDispatcher = Dispatcher.CurrentDispatcher; // not for WinForms } public Dispatcher UIDispatcher { get; private set; } </code></pre> <p>and then, when some event occurs on another thread (thread pool thread in this case):</p> <pre><code>public void Consume(ImageFound message) { var model = _container.Resolve&lt;ChoiceViewModel&gt;(); model.ForImage(message); UIDispatcher.BeginInvoke(new Action(() =&gt; _windows.ShowWindow(model))); } </code></pre> <h3>WinForms equivalent</h3> <p>Don't set UIDispatcher to anything, then you can do have:</p> <pre><code>public void Consume(ImageFound message) { var model = _container.Resolve&lt;ChoiceViewModel&gt;(); model.ForImage(message); this.Invoke( () =&gt; _windows.ShowWindow(model) ); } </code></pre> <h3>DRYing it up for WPF:</h3> <p>Man, so much code...</p> <pre><code>public interface ThreadedViewModel : IConsumer { /// &lt;summary&gt; /// Gets the UI-thread dispatcher /// &lt;/summary&gt; Dispatcher UIDispatcher { get; } } public static class ThreadedViewModelEx { public static void BeginInvoke([NotNull] this ThreadedViewModel viewModel, [NotNull] Action action) { if (viewModel == null) throw new ArgumentNullException("viewModel"); if (action == null) throw new ArgumentNullException("action"); if (viewModel.UIDispatcher.CheckAccess()) action(); else viewModel.UIDispatcher.BeginInvoke(action); } } </code></pre> <p>and in the view model:</p> <pre><code> public void Consume(ImageFound message) { var model = _container.Resolve&lt;ChoiceViewModel&gt;(); model.ForImage(message); this.BeginInvoke(() =&gt; _windows.ShowWindow(model)); } </code></pre> <p>Hope it helps.</p>
 

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