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
76
77
78
79
80
81
82
83
84
using FLY.OBJComponents.IService;
using FObjBase;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FLY.OBJComponents.Server
{
//1min 保存一次数据
public class JsonDist : IJsonDistService
{
public event JsonDistValueChangedEventHandler ValueChanged;
List<DistCell> cells = new List<DistCell>();
public JsonDist()
{
Load();
}
public void GetValue(string key, AsyncCBHandler asyncCB, object asyncContext)
{
var distCell = cells.Find(c => c.Key == key);
asyncCB(asyncContext, distCell);
}
public void SetValue(string key, JObject value)
{
var distCell = cells.Find(c => c.Key == key);
if (distCell == null)
{
distCell = new DistCell()
{
Key = key,
Time = DateTime.Now,
Value = value
};
cells.Add(distCell);
}
else {
distCell.Time = DateTime.Now;
distCell.Value = value;
}
ValueChanged?.Invoke(this, new JsonDistValueValueChangedEventArgs() { key = key });
Save();
}
string file_path = "dist.json";
void Load()
{
if (!File.Exists(file_path))
return;
string json = File.ReadAllText(file_path);
try
{
var cells = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DistCell>>(json);
this.cells = cells;
}
catch
{
//异常
}
if (cells == null)
cells = new List<DistCell>();
}
void Save()
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(cells, Formatting.Indented);
File.WriteAllText(file_path, json);
}
}
}