Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx" rel="nofollow noreferrer">Dispatcher</a>.</p> <p>You can create a class that will hold a dispatcher created on a the main thread and inject it via your container to whatever class executed on a background thread that needs to interact with your main thread.</p> <pre><code>public interface IUiDispatcher { Dispatcher Dispatcher { get; } } public class UiDispatcher : IUiDispatcher { public UiDispatcher() { if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA &amp;&amp; !Thread.CurrentThread.IsBackground &amp;&amp; !Thread.CurrentThread.IsThreadPoolThread) { this.Dispatcher = Dispatcher.CurrentDispatcher; } else { throw new InvalidOperationException("Ui Dispatcher must be created in UI thread"); } } public Dispatcher Dispatcher { get; set; } } public class ExecutedOnABackgroundThread { IUiDispatcher uidispatcher; public ExecutedOnABackgroundThread(IUiDispatcher uidispatcher) { this.uidispatcher = uidispatcher; } public void Method() { // Do something on the background thread... // ... // Now we need to do something on the UI this.uidispatcher.Dispatcher.BeginInvoke(new Action(delegate { // Do something }), null); } } </code></pre> <p>Create the instance of <code>UiDispatcher</code> at a point your are sure your are on the UI thread, for example during the initialization of your application. Using your dependency injection container, ensure that only one instance of this class will be created and injected to any other class that requires it and use it to create/manipulate your UI components.</p> <p>I picked the code to check if the constructor of <code>UiDispatcher</code> is executed in the main thread from <a href="https://stackoverflow.com/a/2374560/1011036">this answer</a>.</p> <p>The thing is that you can't use on the UI thread something created on a different thread. So you need your background thread to delegate to the main UI thread whatever involves UI stuffs.</p>
    singulars
    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.
    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