| 1 | using Core.Librarys.SQLite; |
| 2 | using Core.Servicers.Interfaces; |
| 3 | using System; |
| 4 | using System.Collections.Generic; |
| 5 | using System.Data.SQLite; |
| 6 | using System.Diagnostics; |
| 7 | using System.Linq; |
| 8 | using System.Runtime.CompilerServices; |
| 9 | using System.Text; |
| 10 | using System.Threading; |
| 11 | using System.Threading.Tasks; |
| 12 | |
| 13 | namespace 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 | } |