This article describes the c# example to solve the problem of SQlite concurrent exception method. To share with you for your reference, as follows:

Access to sqlite using c#, often encounter multithreading SQLITE database damage caused by the problem.

SQLite is a file-level database, the lock is the file level : multiple threads can be read at the same time, but only one thread to write. Android provides the SqliteOpenHelper class, adding Java’s locking mechanism for invocation. But does not provide similar functionality in c#.

The author uses the ReaderWriterLock to achieve the goal of multi-thread secure access.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SQLite;
using System.Threading;
using System.Data;
namespace DataAccess
{
/////////////////
public sealed class SqliteConn
{
private bool m_disposed;
private static Dictionary<String, SQLiteConnection> connPool =
new Dictionary<string, SQLiteConnection>();
private static Dictionary<String, ReaderWriterLock> rwl =
new Dictionary<String, ReaderWriterLock>();
private static readonly SqliteConn instance = new SqliteConn();
private static string DEFAULT_NAME = "LOCAL";
#region Init
// Use single case , Solve the problem of initialization and destruction
private SqliteConn()
{
rwl.Add("LOCAL", new ReaderWriterLock());
rwl.Add("DB1", new ReaderWriterLock());
connPool.Add("LOCAL", CreateConn("\\local.db"));
connPool.Add("DB1", CreateConn("\\db1.db"));
Console.WriteLine("INIT FINISHED");
}
private static SQLiteConnection CreateConn(string dbName)
{
SQLiteConnection _conn = new SQLiteConnection();
try
{
string pstr = "pwd";
SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
connstr.DataSource = Environment.CurrentDirectory + dbName;
_conn.ConnectionString = connstr.ToString();
_conn.SetPassword(pstr);
_conn.Open();
return _conn;
}
catch (Exception exp)
{
Console.WriteLine("===CONN CREATE ERR====\r\n{0}", exp.ToString());
return null;
}
}
#endregion
#region Destory
// Manual control of the destruction , Ensure data integrity
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (!m_disposed)
{
if (disposing)
{
// Release managed resources
Console.WriteLine(" Close local DB Connect ...");
CloseConn();
}
// Release unmanaged resources
m_disposed = true;
}
}
~SqliteConn()
{
Dispose(false);
}
public void CloseConn()
{
foreach (KeyValuePair<string, SQLiteConnection> item in connPool)
{
SQLiteConnection _conn = item.Value;
String _connName = item.Key;
if (_conn != null && _conn.State != ConnectionState.Closed)
{
try
{
_conn.Close();
_conn.Dispose();
_conn = null;
Console.WriteLine("Connection {0} Closed.", _connName);
}
catch (Exception exp)
{Console.WriteLine(" Serious anomaly : Unable to close local DB {0} Connection 。", _connName);
exp.ToString();}finally{
_conn =null;}}}}#endregion#region GetConnpublicstaticSqliteConnGetInstance(){return instance;}publicSQLiteConnectionGetConnection(string name){SQLiteConnection _conn = connPool[name];try{if(_conn !=null){Console.WriteLine("TRY GET LOCK");// Lock , Until the release , Other threads can't get conn
rwl[name].AcquireWriterLock(3000);Console.WriteLine("LOCK GET");return _conn;}}catch(Exception exp){Console.WriteLine("===GET CONN ERR====\r\n{0}", exp.StackTrace);}returnnull;}publicvoidReleaseConn(string name){try{// release Console.WriteLine("RELEASE LOCK");
rwl[name].ReleaseLock();}catch(Exception exp){Console.WriteLine("===RELEASE CONN ERR====\r\n{0}", exp.StackTrace);}}publicSQLiteConnectionGetConnection(){returnGetConnection(DEFAULT_NAME);}publicvoidReleaseConn(){ReleaseConn(DEFAULT_NAME);}#endregion}}////////////////////////

The code is invoked as follows:

SQLiteConnection conn = null;
try
{
conn = SqliteConn.GetInstance().GetConnection();
// Write your own code here.
}
finally
{
SqliteConn.GetInstance().ReleaseConn();
}

It is worth noting that each application connection, you must use the ReleaseConn method to release, otherwise the other thread can no longer be connected.

For security reasons, the most stringent read and write lock restrictions are enabled in the tool class written by the author (ie, they can not be read at the time of writing). If the data is read frequently, the reader can also develop a way to get read-only connections to improve performance.

c# Resolve SQlite Concurrency Exception Problem (Using Read-Write Lock)的更多相关文章

  1. mongodb exception in initAndListen: 12596 old lock file, terminating 解决方法

    错误信息如下: exception in initAndListen: 12596 old lock file, terminating 基本上都是由于服务器断电等异常中断重启引起 解决方法 1.删除 ...

  2. exception in initAndListen: 12596 old lock file, terminating

    #mongd -f /etc/mongodb.conf时报错 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamFjc29uX2JhaQ==/font/5a ...

  3. resolve some fragment exception

    1.android fragment not attached to activity http://blog.csdn.net/walker02/article/details/7995407 if ...

  4. 《深入浅出 Java Concurrency》—锁紧机构(一)Lock与ReentrantLock

    转会:http://www.blogjava.net/xylz/archive/2010/07/05/325274.html 前面的章节主要谈谈原子操作,至于与原子操作一些相关的问题或者说陷阱就放到最 ...

  5. 深入浅出 Java Concurrency (6): 锁机制 part 1 Lock与ReentrantLock

      前面的章节主要谈谈原子操作,至于与原子操作一些相关的问题或者说陷阱就放到最后的总结篇来整体说明.从这一章开始花少量的篇幅谈谈锁机制. 上一个章节中谈到了锁机制,并且针对于原子操作谈了一些相关的概念 ...

  6. mongodb exception in initAndListen: 12596 old lock file, terminating解决方法

    错误信息如下: exception old lock file, terminating 解决方法 .删除data目录中的.lock文件 .mongod.exe --repair .启动mongod就 ...

  7. Entity Framework Tutorial Basics(28):Concurrency

    Concurrency in Entity Framework: Entity Framework supports Optimistic Concurrency by default. In the ...

  8. HybridApp Exception

    HybridApp Exception [创建安卓虚拟机失败]CPU acceleration status:HAXM must be updated(version 1.1.1<6.0.1) ...

  9. Java Concurrency - ReadWriteLock & ReentrantReadWriteLock

    锁所提供的最重要的改进之一就是 ReadWriteLock 接口和它的实现类 ReentrantReadWriteLock.这个类提供两把锁,一把用于读操作和一把用于写操作.同一时间可以有多个线程执行 ...

随机推荐

  1. 你真的理解Python中MRO算法吗?[转]

    [前言] MRO(Method Resolution Order):方法解析顺序.Python语言包含了很多优秀的特性,其中多重继承就是其中之一,但是多重继承会引发很多问题,比如二义性,Python中 ...

  2. class ObjectOutputStream也是过滤流,使节点流直接获得输出对象。

    class ObjectOutputStream也是过滤流,使节点流直接获得输出对象. 最有用的方法:WriteObject(Object b) 用流传输对象称为对象的序列化,但并不使所有的对象都可以 ...

  3. windows 10系统 上安装scrapy

    1.python的安装(我已安装完) 2.pip的安装(我已安装) 3.安装twisted https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted 命令 ...

  4. LVS & NGINX

      LVS NGINX

  5. Power BI数据网关

      前言 你的组织中的用户可以访问本地数据(他们已经具有该数据的访问授权),但在这些用户可以连接到你的本地数据源之前,需要安装和配置本地数据网关. 该网关便于云中的用户与你的本地数据源相互进行快速安全 ...

  6. 在mysql中给查询的结果添加序号列

    SELECT * FROM ( SELECT (@i:=@i+1) as i, id, data_send_time FROM jl_pims_machine_time mt,(select @i:= ...

  7. nvm的安装

    安装前可先卸载原来的node, npm, 安装成功后,可用nvm装node 一.用nvm-noinstall.zip安装 1.nvm-windows 下载 https://github.com/cor ...

  8. roadhog 介绍

    官方网站:https://www.npmjs.com/package/roadhog; 项目搭建demo: https://github.com/ght5935/antd-dva-less-webpa ...

  9. 用 ArrayList 集合调用商品类

    public class  Commodity{ //定义商品类 String name; //定义商品名字 double  size;  //定义商品尺寸 double  price; //定义商品 ...

  10. elk-准备(一)

    一.在搭建elk之前需要做准备工作 1.创建elk用户 groupadd elk -g 1001 useradd elk -m -d /home/elk -s /bin/bash -g 1001 -u ...