Accessing UI (Main) Thread safely in WPF
Solution 1:
You can use
Dispatcher.Invoke(Delegate, object[])
on the Application
's (or any UIElement
's) dispatcher.
You can use it for example like this:
Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
or
someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
Solution 2:
The best way to go about it would be to get a SynchronizationContext
from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher
directly). For example:
class MyViewModel
{
private readonly SynchronizationContext _syncContext;
public MyViewModel()
{
// we assume this ctor is called from the UI thread!
_syncContext = SynchronizationContext.Current;
}
// ...
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
_syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
}
}
Solution 3:
Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.
Step 1. Use the following namespaces
using System.Windows;
using System.Threading;
using System.Windows.Threading;
Step 2. Put the following line where you need to update UI
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
//Update UI here
}));
Syntax
[BrowsableAttribute(false)] public object Invoke( DispatcherPriority priority, Delegate method )
Parameters
priority
Type:
System.Windows.Threading.DispatcherPriority
The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.
method
Type:
System.Delegate
A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.
Return Value
Type:
System.Object
The return value from the delegate being invoked or null if the delegate has no return value.
Version Information
Available since .NET Framework 3.0