[英]c# - Entity framework multi threading
i want to remove entities on a background thread but we can not delete entities on another thread that it has be created on so how can i do that and keep the ui responding? 我想删除后台线程上的实体,但是我们不能删除已在其上创建的另一个线程上的实体,所以我该怎么做并保持ui响应? i'm tying to use the backgroundworker class here is the code 我想使用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);
}
Don't use 'foreach' to delete entities. 不要使用“ foreach”来删除实体。 When you delete a entity,the source is changed, it may throw an exception. 删除实体时,源会更改,它可能会引发异常。 Use 'for' instead. 使用“ for”代替。 And why you delete it in a new thread?UI will be updated when all of the delete operations are finished. 以及为什么要在新线程中删除它?所有删除操作完成后,UI将会更新。
try like this: 尝试这样:
UI(List): itemsource={Binding LstTest} UI(列表):itemsource = {Binding LstTest}
background: 背景:
deletePeriodWorker_DoWork() { 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
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.