DispatcherService
- 3 minutes to read
The DispatcherService is an IDispatcherService implementation that allows you to perform actions in a ViewModel using the Dispatcher.
Getting Started with DispatcherService
To perform an action in a ViewModel using the Dispatcher, use the DispatcherService. Add the service to the view’s dxmvvm:Interaction.Behaviors.
<UserControl x:Class="DXSample.View.MainView"
...
xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
xmlns:vm="clr-namespace:DXSample.ViewModel"
DataContext="{dxmvvm:ViewModelSource Type=vm:MainViewModel}">
...
<dxmvvm:Interaction.Behaviors>
<dxmvvm:DispatcherService />
</dxmvvm:Interaction.Behaviors>
...
</UserControl>
Use the following approaches to access the defined DispatcherService from your ViewModel:
To perform the required actions, use the BeginInvoke(Action) method, as shown in the code snippet below.
[POCOViewModel]
public class MainViewModel {
protected IDispatcherService DispatcherService { get { return this.GetService<IDispatcherService>(); } }
...
void CalcCore() {
...
DispatcherService.BeginInvoke(() => { ... });
...
}
...
}
The DispatcherService includes the following properties:
- DispatcherPriority – gets or sets the DispatcherService’s Dispatcher priority by which operations can be invoked by the Dispatcher.
- Delay – gets or sets the amount of time (a TimeSpan object) to wait before invoking the DispatcherService.BeginInvoke method.
using DevExpress.Mvvm;
using DevExpress.Mvvm.POCO;
using DevExpress.Mvvm.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
namespace DXSample.ViewModel {
[POCOViewModel]
public class MainViewModel {
public virtual int Progress { get; protected set; }
public virtual Brush Color { get; protected set; }
public virtual bool IsProgress { get; protected set; }
protected IDispatcherService DispatcherService { get { return this.GetService<IDispatcherService>(); } }
public void Calculate() {
IsProgress = true;
Task.Factory.StartNew(CalcCore).ContinueWith(x => {
DispatcherService.BeginInvoke(() => IsProgress = false);
});
}
protected void OnIsProgressChanged() {
this.RaiseCanExecuteChanged(x => x.Calculate());
}
public bool CanCalculate() {
return !IsProgress;
}
void CalcCore() {
for (int i = 1; i <= 100; i++) {
DispatcherService.BeginInvoke(() => {
Progress = i;
Color = new SolidColorBrush(GetColor(i));
});
Thread.Sleep(TimeSpan.FromSeconds(0.1));
}
}
Color GetColor(int coef) {
return new Color() {
R = (byte)(coef * 15),
G = (byte)(coef * 7),
B = (byte)(coef * 8),
A = 255,
};
}
}
}