当我试图同时执行两个不同的实体框架查询时,它给出了一个异常,如下所示
A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe我知道这是因为_context在多线程中的并行执行。但有没有其他方法可以同时实现这两个结果呢?这是我的代码。
try
{
using (_Context)
{
List<AllotedQuotas> allotedQuotas = new List<AllotedQuotas>();
List<Quotas> quotas = new List<Quotas>();
Thread t1 = new Thread(() =>
{
AllotedQuotas ob = new AllotedQuotas(_Context);
allotedQuotas = ob.GetAllotedQuotas(pid);
});
Thread t2 = new Thread(() =>
{
quotas = _Context._quotas.ToList();
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
var QuotasList = quotas.Join(allotedQuotas, QID => QID.ID, AID => AID.Quota_ID,
(_QutasName, _Alloted) => new Quotas
{
ID = _QutasName.ID,
Quota_Name = _QutasName.Quota_Name,
Active = _QutasName.Active
}).ToList();
return QuotasList;
}
}
catch (Exception ex)
{
throw ex.InnerException ?? ex;
}发布于 2019-01-29 20:12:19
在前一个操作完成之前在此上下文上启动的第二个操作。不保证任何实例成员都是线程安全的。
正如错误消息清楚地描述的那样,您的主要问题是在不同线程之间获得冲突。要解决此问题,您可以使用mutex或lock语句在所需的时间内仅为一个线程分配资源,并等待其他线程,直到资源空闲。对于lock语句,您可以检查here。要了解线程(基础知识和更多),您可以查看this的伟大页面。
https://stackoverflow.com/questions/54416214
复制相似问题