跳到主要内容

github/tai

公开

Tai · Windows 软件与网站使用时长统计。上游 Planshit/Tai 的源码镜像,非灵栈原创;MIT 许可。来源:https://github.com/Planshit/Tai 。本次为手动同步,暂不提供安装包。

浏览文件

Database.cs

90 行 · 2.5 KB历史下载
1using Core.Librarys.SQLite;
2using Core.Servicers.Interfaces;
3using System;
4using System.Collections.Generic;
5using System.Data.SQLite;
6using System.Diagnostics;
7using System.Linq;
8using System.Runtime.CompilerServices;
9using System.Text;
10using System.Threading;
11using System.Threading.Tasks;
12
13namespace Core.Servicers.Instances
14{
15 public class Database : IDatabase
16 {
17 private TaiDbContext _writerContext;
18 private readonly object _writeLocker = new object();
19 private readonly object _readLocker = new object();
20 private readonly object _closeLocker = new object();
21 private int _outTime = 60;
22 private int _readerNum = 0;
23 private bool _isWriting = false;
24 private bool _isReading = false;
25 public TaiDbContext GetReaderContext()
26 {
27 lock (_readLocker)
28 {
29 _isReading = true;
30 int duration = 0;
31 while (_isWriting)
32 {
33 Thread.Sleep(1000);
34 duration++;
35 if (duration >= _outTime)
36 {
37 break;
38 }
39 }
40 _writerContext?.Dispose();
41 _readerNum++;
42 var db = new TaiDbContext();
43 db.Database.Connection.StateChange += Connection_StateChange;
44 return db;
45 }
46 }
47
48 private void Connection_StateChange(object sender, System.Data.StateChangeEventArgs e)
49 {
50 if (e.CurrentState == System.Data.ConnectionState.Closed)
51 {
52 _readerNum--;
53 _isReading = _readerNum > 0;
54 }
55 }
56
57 public void CloseReader()
58 {
59 }
60
61 public TaiDbContext GetWriterContext()
62 {
63 lock (_writeLocker)
64 {
65 int duration = 0;
66 while (_isWriting || _isReading)
67 {
68 Thread.Sleep(1000);
69 duration++;
70 if (duration >= _outTime)
71 {
72 break;
73 }
74 }
75 _isWriting = true;
76 _writerContext = new TaiDbContext();
77 return _writerContext;
78 }
79 }
80
81 public void CloseWriter()
82 {
83 lock (_closeLocker)
84 {
85 _writerContext?.Dispose();
86 _isWriting = false;
87 }
88 }
89 }
90}