我想删除后台线程上的实体,但是我们无法删除已在其上创建的另一个线程上的实体,那么我该如何做并保持ui响应?我想在这里使用backgroundworker类是代码
void deletePeriodWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(3000);
List<Period> selectedPeriods = e.Argument as List<Period>;
foreach (Period period in selectedPeriods)
{
while (period.Transactions.Count > 0)
{
Transaction transaction = period.Transactions[0];
this.Dispatcher.Invoke(new Action(() => context.Transactions.Remove(transaction)),
System.Windows.Threading.DispatcherPriority.Normal);
}
this.Dispatcher.Invoke(new Action(() => context.Periods.Remove(period)),
System.Windows.Threading.DispatcherPriority.Normal);
}
this.Dispatcher.Invoke(new Action(() => context.SaveChanges()),
System.Windows.Threading.DispatcherPriority.Normal);
}
答案 0 :(得分:2)
不要使用&#39; foreach&#39;删除实体。删除实体时,源会更改,它可能会引发异常。使用&#39;用于&#39;代替。为什么要在新线程中删除它?在完成所有删除操作后,UI将会更新。
尝试这样:
UI(列表):itemsource = {Binding LstTest}
背景:
deletePeriodWorker_DoWork() {
List<Period> selectedPeriods = e.Argument as List<Period>;
foreach (Period period in selectedPeriods)
{
while (period.Transactions.Count > 0)
{
//operation
}
//ui updating
this.Dispatcher.Invoke(new Action(() => LstTest.Remove(period)),
System.Windows.Threading.DispatcherPriority.Normal);
//EF updating
context.Periods.Remove(period);
}
//context savechanges
}