Reputation: 466
I've this class, it works fine
public partial class Home : UserControl
{
public ObservableCollection<Activity> DataGridRows { get; set; }// = new ObservableCollection<Activity>();
public Home()
{
InitializeComponent();
DataContext = this;
this.Init();
}
private void Init()
{
DataGridRows = new ObservableCollection<Activity>();
refreshGrid(null, null);
}
private void refreshGrid(object sender, RoutedEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
startRefresh(); //<-- very long operation!
}));
}
}
My problem is that while calling startRefresh() the whole program is freezed, i can't click on other buttons or perform other operations until startRefresh is finished. However i want to run it on background. Note that i can't use the Task object with the TaskScheduler.FromCurrentSynchronizationContext() method because startRefresh performs edit operations on DataGridRows and i get this exception:
System.NotSupportedException : This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
Upvotes: 0
Views: 2173
Reputation: 2741
I think you can use awaitable delegate command
public ICommand MyCommand { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
MyCommand = new AwaitableDelegateCommand(refreshGrid);
}
private async Task refreshGrid()
{
await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
Thread.Sleep(10000);
}));
}
You can have a look at http://jake.ginnivan.net/awaitable-delegatecommand/ for awaitable delegate command
Upvotes: 0
Reputation: 388
You need to move the heavy data fetching and processing off the UI thread. When the data is ready, update the UI from the UI thread. If you are using .NET 4.0 or later, the Task Parallel Library makes this sort of operation MUCH easier.
NOTE: I am making the assumption that startRefresh()
both fetches data and updates the UI. You will make like much easier on yourself if the data retrieval and UI update are in separate methods.
See this answer for more detail: Avoiding the window (WPF) to freeze while using TPL
Upvotes: 1