forked from mchidk/BinaryRage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB.cs
75 lines (62 loc) · 2.16 KB
/
DB.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using BinaryRage.Functions;
namespace BinaryRage
{
static public class DB<T>
{
static BlockingCollection<SimpleObject> sendQueue = new BlockingCollection<SimpleObject>();
private static int writeCounter;
static public void WaitForCompletion()
{
while (writeCounter > 0)
Thread.Sleep(10);
}
static public void Insert(string key, T value, string filelocation)
{
Interlocked.Increment(ref writeCounter);
SimpleObject simpleObject = new SimpleObject {Key = key, Value = value, FileLocation = filelocation};
sendQueue.Add(simpleObject);
var data = sendQueue.Take(); //this blocks if there are no items in the queue.
ThreadPool.QueueUserWorkItem(state =>
{
//Add to cache
Interlocked.Increment(ref Cache.counter);
Cache.CacheDic[filelocation + key] = simpleObject;
Storage.WritetoStorage(data.Key, Compress.CompressGZip(ConvertHelper.ObjectToByteArray(value)), data.FileLocation);
Interlocked.Decrement(ref writeCounter);
});
}
static public void Remove(string key, string filelocation)
{
if (!Cache.CacheDic.IsEmpty)
{
SimpleObject value;
Cache.CacheDic.TryRemove(filelocation + key, out value);
}
File.Delete(Storage.GetExactFileLocation(key, filelocation));
}
static public T Get(string key, string filelocation)
{
//Try getting the object from cache first
if (!Cache.CacheDic.IsEmpty)
{
SimpleObject simpleObjectFromCache;
if (Cache.CacheDic.TryGetValue(filelocation + key, out simpleObjectFromCache))
return (T) simpleObjectFromCache.Value;
}
byte[] compressGZipData = Compress.DecompressGZip(Storage.GetFromStorage(key, filelocation));
T umcompressedObject = (T)ConvertHelper.ByteArrayToObject(compressGZipData);
return umcompressedObject;
}
static public bool Exists(string key, string filelocation)
{
return Storage.ExistingStorageCheck(key, filelocation);
}
}
}