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. Webpack前端打包工具

    一.安装 安装Webpack之前需要安装nodejs,然后用npm安装: $ npm install webpack -g &nsbp;运行以上命令就将Webpack安装到了全局环境中.  但 ...

  2. E - Closest Common Ancestors

    Write a program that takes as input a rooted tree and a list of pairs of vertices. For each pair (u, ...

  3. mac npm编译的时候,一直报 node 镜像找不到

    目前我所知的方法就是卸载.重装node,或者是升级node 卸载: brew uninstall node 安装: brew install node 升级: brew upgrade node

  4. 【C++ 模板迭代器实例/半素数】

    题目:判断一个数是不是两个素数的乘积,是输出YES,不是输出NO.数据范围为2-1000000. 为了解决这个问题,我们继续使用STL——vector & set,分别用来存储素数和半素数.为 ...

  5. Oracle tablespace 创建表空间

    定义: 表空间是一个逻辑概念,它的所有数据和结构信息都存储在一个或多个数据文件中,表空间属于数据库的一部分.数据库自带有几个表空间,如system,temp.一般系统将创建几个私用或业务的表空间. 模 ...

  6. Hadoop 跨集群访问

    [原文地址] 跨集群访问 发表于 2015-06-01   |   简单总结下跨集群访问的多种方式. 跨集群访问HDFS 直接给出HDFS URI 我们平常执行hadoop fs -ls /之类的操作 ...

  7. C# word 图片大小

    通过Office自带的类库word文档中插入图片,图片大小的单位为磅 而文档中,图片的大小已经固定,为CM. 实际工作中,首先将图片插入到word中,根据目前的大小,计算转换为目标大小的比率,将长宽按 ...

  8. IDEA多个服务打断点 各服务乱窜的问题

    Setting --> Build, Execution, Deployment --> Debugger 选中即可

  9. 编写函数求整形数组a中存储的m个不重复的整数的第k大的整数(其中m>=1,1<=k<=m)很简单的一个思路是酱紫的:管他辣么多干啥,上来一把排序然后直接得答案

    /** * @author:(LiberHome) * @date:Created in 2019/2/28 20:38 * @description: * @version:$ *//*编写函数求整 ...

  10. leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation

    leetcode 逆波兰式求解 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid ope ...