c# Resolve SQlite Concurrency Exception Problem (Using Read-Write Lock)
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)的更多相关文章
- mongodb exception in initAndListen: 12596 old lock file, terminating 解决方法
错误信息如下: exception in initAndListen: 12596 old lock file, terminating 基本上都是由于服务器断电等异常中断重启引起 解决方法 1.删除 ...
- exception in initAndListen: 12596 old lock file, terminating
#mongd -f /etc/mongodb.conf时报错 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamFjc29uX2JhaQ==/font/5a ...
- resolve some fragment exception
1.android fragment not attached to activity http://blog.csdn.net/walker02/article/details/7995407 if ...
- 《深入浅出 Java Concurrency》—锁紧机构(一)Lock与ReentrantLock
转会:http://www.blogjava.net/xylz/archive/2010/07/05/325274.html 前面的章节主要谈谈原子操作,至于与原子操作一些相关的问题或者说陷阱就放到最 ...
- 深入浅出 Java Concurrency (6): 锁机制 part 1 Lock与ReentrantLock
前面的章节主要谈谈原子操作,至于与原子操作一些相关的问题或者说陷阱就放到最后的总结篇来整体说明.从这一章开始花少量的篇幅谈谈锁机制. 上一个章节中谈到了锁机制,并且针对于原子操作谈了一些相关的概念 ...
- mongodb exception in initAndListen: 12596 old lock file, terminating解决方法
错误信息如下: exception old lock file, terminating 解决方法 .删除data目录中的.lock文件 .mongod.exe --repair .启动mongod就 ...
- Entity Framework Tutorial Basics(28):Concurrency
Concurrency in Entity Framework: Entity Framework supports Optimistic Concurrency by default. In the ...
- HybridApp Exception
HybridApp Exception [创建安卓虚拟机失败]CPU acceleration status:HAXM must be updated(version 1.1.1<6.0.1) ...
- Java Concurrency - ReadWriteLock & ReentrantReadWriteLock
锁所提供的最重要的改进之一就是 ReadWriteLock 接口和它的实现类 ReentrantReadWriteLock.这个类提供两把锁,一把用于读操作和一把用于写操作.同一时间可以有多个线程执行 ...
随机推荐
- MYSQL数据库高可用方案探究
MySQL作为最关键的应用数据存储中心,如何保证MySQL服务的可靠性和持续性,是我们不得不细致考虑的一个问题.当master宕机的时候,我们如何保证数据尽可能的不丢失,如何保证快速的获知master ...
- Win7 SP1 32位 旗舰版 IE8 快速稳定 纯净优化 无人值守 自动激活 20170518
一.系统特色 1.采用微软原版旗舰版定制而成. 2.优化系统服务,关闭一些平时很少使用的服务. 3.精简掉一些无用的东西. 4.系统全程离线制作,不包含任何恶意插件,放心使用. 5.右下角时间加上星期 ...
- JavaScript鼠标拖动div且可调整div大小
http://www.softwhy.com/article-5502-1.html <!DOCTYPE html> <html> <head> <meta ...
- oracle 优化or 更换in、exists、union all几个字眼
oracle 优化or 更换in.exists.union几个字眼.测试没有问题! 根据实际情况选择相应的语句是.假设指数,or全表扫描,in 和not in 应慎用.否则会导致全表扫描. sele ...
- Python3集合
集合(set)是一个无序的不重复元素序列. 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典. 创建格 ...
- 3D游戏图形引擎
转自:http://www.cnblogs.com/live41/archive/2013/05/11/3072282.html CryEngine 3 http://www.crydev.net/ ...
- 并发编程(CountDownLatch使用)
一.简介: Latch意思是:门闩的意思,形象的来说await就是拴上门闩,等到门闩释放后当前线程开始工作. 下面是来自简书上的解释: CountDownlatch是一个多功能的同步工具,可以被用于各 ...
- 转 .NET4.5之初识async与await
来自:http://www.cnblogs.com/lekko/archive/2013/03/05/2944282.html 本人是从.NET4.0刚出的时候接触的.NET环境,所以学的东西就是4. ...
- 关于vmware 11.1安装windows 7操作系统时报错 Unist specified don’t exist. SHSUCDX can’t install
笔者今天在vmware 11.1 虚拟机下使用光驱安装windows 7 32位操作系统时,报错: Unist specified don’t exist. SHSUCDX can’t install ...
- Linux下的搜索查找命令的详解(find)
4.find Linux下find命令在目录结构中搜索文件,并执行指定的操作.Linux下find命令提供了相当多的查找条件,功能很强大.由于find具有强大的功能,所以它的选项也很多,其中大部分选项 ...