我对 WPF 很陌生。我正在开发一个 PRISM 应用程序,并希望在更新可枚举时更新 UI。我在我的模型视图中使用 backgroundWorker 来更新枚举。一切正常,直到它自己的枚举被更新然后用户界面冻结!一位朋友告诉我,我也许可以使用yield
关键字,但我不太明白。
这是代码:
public void ChangeCollection()
{
BackgroundWorker worker = new BackgroundWorker();
// Set workers job
worker.DoWork += (sender, e) =>
{
RunOnUIThread(() => IsBusy = true);
e.Result = GetPrimes();
};
// On Complete
worker.RunWorkerCompleted += (sender, e) =>
{
RunOnUIThread(() =>
{
IsBusy = false;
// HERE IS WHERE IT GETS STUCK
Numbers = new ObservableCollection<int>
((IEnumerable<int>)e.Result);
});
};
// Start background operation
worker.RunWorkerAsync();
}
public ObservableCollection<int> Numbers
{
get {return _Numbers;}
set
{
_Numbers = value;
RaisePropertyChanged(() => Numbers);
}
}
public IEnumerable<int> GetPrimes()
{
List<int> primes = new List<int>();
for (int i = 0; i < 100000; i++)
{
bool IsPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
IsPrime = false;
}
if (IsPrime)
primes.Add(i);
}
return primes;
}
任何建议将不胜感激!
谢谢,暗里