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. fiddler 中显示请求 IP

    在 Rules -> Customize Rules... 中,static function Main() 中加一行 FiddlerObject.UI.lvSessions.AddBoundC ...

  2. 接口和多态都为JAVA技术的核心。

    类必须实现接口中的方法,否则其为一抽象类. 实现中接口和类相同.   接口中可不写public,但在子类中实现接口的过程中public不可省. (如果剩去public则在编译的时候提示出错:对象无法从 ...

  3. 真-关闭win10安全中心(windows defender)

    狂客原创,转载请注明.侵权必究 第一 任务管理器 启动项 禁用 第二 使用win+R,打开运行命令输入:gpedit.msc然后点击确定 在管理模块下找到Windows组件,接续打开下拉菜单,找到Wi ...

  4. 【Py-Github】根据条件筛选Github repo的例子

    条件: language:python commits:>100 contributors:>2 stars:>5 fork:0 实现: from github import Git ...

  5. 离线提取域控HASH的方法

    1.注册表提取 提取文件,Windows Server 2003或者Win XP 及以前需要提升到system权限,以后只要Administrator权限即可. reg save hklm\sam s ...

  6. Keil不能跳转到函数的定义怎么办

    有时候我们右键一个函数名并点击Go To Definition Of xxx时,Keil却提示无法找到定义.但这个函数确实有定义的.这个时候可以试着重新编译整个工程,即可跳转到定义了.

  7. Java编程基础篇第一章

    计算机语言 人与计算机交流的方式. 计算机语言有很多种如:C语言,c++,Java等 人机交互 软件的出现实现了人与计算机之间的更好的交流(交互) 交互方式 图形化界面:便于交互,容易操作,简单直观, ...

  8. 渗透常用dos命令,http协议及数据提交方式。 hack 某某

    dir查看目录 cd 切换目录 strat www.xxx.com   打开网页 del 删除文件 cls 清屏幕命令 ipconfig  查看ip地址 netstat -an   显示网络连接.路由 ...

  9. sql中join与left-join图解区别

      select a.* from YG_BRSYK a left join(SELECT DISTINCT SYXH, STUFF((SELECT '.'+MS FROM #lsb where SY ...

  10. 2018-2019-2 网络对抗技术 20165318 Exp2 后门原理与实践

    2018-2019-2 网络对抗技术 20165318 Exp2 后门原理与实践 后门的基本概念及基础问题回答 常用后门工具 netcat Win获得Linux Shell Linux获得Win Sh ...