简体   繁体   English

如何同步访问数据库,一次一个线程

[英]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.

相关问题 如何从另一个线程同步UI和访问对象? - How to synchronize UI and access objects from another thread? 将Oracle数据库同步到Access数据库 - Synchronize Oracle database to Access database 如何在C#中自动进行数据库访问和DatagridView之间的同步 - How to do Automatic synchronize between database access and DatagridView in c# 如何在启动时同步Windows服务对SQL Server数据库的访问? - How to Synchronize Windows Service Access to SQL Server Database on Startup? 如何从另一个线程访问 WinForms 控件,即与 GUI 线程同步? - How to access a WinForms control from another thread i.e. synchronize with the GUI thread? 我应该*始终*同步访问从多个线程使用的所有双字段/属性/变量? - should I *always* synchronize access to all double field/property/variables that used from more than one thread? 如何使用Consul一次在一台机器上执行同步任务? - How to use Consul to perform synchronize task on one machine at a time? 如何将DataTables与数据库同步 - How to synchronize DataTables with database 如何同步Database和DataGridView - How to synchronize Database and DataGridView 我是否需要同步对int的线程访问? - Do I need to synchronize thread access to an int?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM