我這個類,它工作正常避免凍結UI,同時加載
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!
}));
}
}
我的問題是,儘管調用startRefresh()整個程序被凍結,我不能點擊其他按鈕或執行其他操作,直到startRefresh完成。但是我想在後臺運行它。 注意,因爲startRefresh上DataGridRows進行編輯操作和我得到這個例外,我不能與TaskScheduler.FromCurrentSynchronizationContext()方法使用Task對象:
System.NotSupportedException : This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
您可以使用[後臺工作(https://msdn.microsoft.com/en-us/library/cc221403(v = VS.95)的.aspx) –
你需要看看使用BackgroundWorkerThread加載數據多線程。 – ChrisF
有關NotSupportedException異常:http://stackoverflow.com/questions/35359923/visual-basic-net-timer-vs-thread/35363155#35363155(這是在VB .NET中,但相同的概念)。因此,在您StartRefresh方法,則必須調用無論您何時更新的DataGrid –