我的应用程序中有76个复选框。我想在选中任何复选框时从数据库中读取一些值。要读取这些值,每次选中复选框时都会创建一个后台工作程序。
如果我逐个检查这些复选框,则没有问题。但是,如果我立即检查它们,我的数据库代码会抛出一个EntityException
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
BackgroundWorker worker1 = new BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(worker1_DoWork);
worker1.RunWorkerAsync(sender);
}
void worker1_DoWork(object sender, DoWorkEventArgs e)
{
if (((CheckBox)e.Argument).Checked == true)
{
....Some Codes
var vv = (from value in d.tblValue join addres in d.tblAddres on value.AddresID equals addres.ID where value.AddresID == addresID && value.LoopDate >= startDate && value.LoopDate<= finishDate orderby value.LoopDate select new { value, addres }).ToList();
....Some Codes
}
}
是否因为我对数据库负担过重而导致此错误?
答案 0 :(得分:1)
看起来您正在重新使用以前创建的DbContext
(变量d
),这不一定是线程安全的。尝试在DbContext
方法中创建新的worker1_DoWork
(不要重复使用单个实例)。
void worker1_DoWork(object sender, DoWorkEventArgs e)
{
if (((CheckBox)e.Argument).Checked == true)
{
....Some Codes
using(var db = new MyFooEntities())
{
var vv = (from value in db.tblValue
join addres in db.tblAddres on value.AddresID equals addres.ID
where value.AddresID == addresID &&
value.LoopDate >= startDate &&
value.LoopDate<= finishDate
orderby value.LoopDate
select new { value, addres }).ToList();
}
....Some Codes
}
}