[英]How to synchronize access to a database, one thread at a time
I have developed a Windows Service in C# that receives events from an external hardware. 我已经用C#开发了Windows服务,该服务从外部硬件接收事件。 For each received event, a SQLite database creates a record and save it. 对于每个收到的事件,SQLite数据库都会创建一条记录并保存。
The problem is that from time to time, a DBLock error occurs, so I need to control that only one thread can write to the database at a time. 问题是,有时会发生DBLock错误,因此我需要控制一次只能有一个线程写入数据库。
I have created this class variable that is instantiated in Service OnStart method: 我创建了在Service OnStart方法中实例化的此类变量:
private DataWare.monitorEntities _db;
Then, in the event, I have: 然后,在事件中,我有:
void driver_Transaccion(object sender, AttendanceReader.MarcacionEventArgs e)
{
lock (_db)
{
/* Code that creates a record a does some other actions */
/* ......... */
_db.SaveChanges();
}
}
The problem is that I continue receiving the DBLock exception, so, it seems the instruction lock (_db) is not taken into account. 问题是我继续收到DBLock异常,因此似乎未考虑指令锁(_db)。
Any help, please? 有什么帮助吗?
Are you disposing your connection after usage? 使用后是否要处置连接?
lock (_lockObj)
{
using (MyEntities context = new MyEntities)
{
// do stuff
context.SaveChanges();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.