1.情景
很多时候,我们系统重新启动的时候,数据需要备份,这时候为了保证重启的过程中数据不丢失我们一般采取把数据入库的方法,但时很多时候,一些数据入库时没有必要的,这些数据不具备业务价值,且变化频率非常低,可能一天也就变化几次。但是系统每一次交互还都需要,而每天的交互量可能时毫秒频率的。这种数据持续与数据库交互时完全没有必要的,但如果放在内存种,又要担心重启等情况。这些数据如果面临断电了,那么系统需要重新服务运行即可,也就时说这种数据也不是那么必须一定要时实保存。这种数据最适合的处理方式是常驻内存,在系统关闭的时候保存,在开启的时候自动读取。那么我想如果又一个有自己备份功能的类就好了,我们解决这个问题就很轻松了。
2.举例 需求
我把上面的这个情景用一个具体的需求体现处理,就是一个不断的计算程序,重启的时候计数仍然能够接续下去。
3.代码
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 系统关闭的时候备份数据
{
/// <summary>
/// ui承载类
/// </summary>
public partial class Form1 : Form
{
MainThrend mainThrend;
public Form1()
{
InitializeComponent();
mainThrend = new MainThrend(label1);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mainThrend.close();
}
}
/// <summary>
/// 系统主线程类
/// 注意承载一个系统运行的主要逻辑
/// </summary>
class MainThrend: IBindClose
{
MyData myData = new MyData();
private readonly Label label;
public MainThrend(Label label)
{
this.label = label;
Task task = new Task(() =>
{
run();
});
task.Start();
}
public void run()
{
while (true)
{
Thread.Sleep(200);
myData.index++;
Action<String> AsyncUIDelegate = delegate (string n) { label.Text = n; };//定义一个委托
label.Invoke(AsyncUIDelegate, new object[] { myData.index.ToString() });
}
}
public void close()
{
myData.close();
}
}
/// <summary>
/// 测试用的实例
/// </summary>
[Serializable]
class MyData: BindClose
{
public int index = 0;
public MyData()
{
load();
}
protected override void LoadData(object o)
{
MyData myData = (MyData)o;
this.index = myData.index;
}
}
/// <summary>
/// 绑定具有备份功能的接口
/// </summary>
interface IBindClose
{
void close();
}
/// <summary>
/// 具有自己备份功能的类
/// 关闭的时候备份数据
/// 构造的时候重新加载备份的数据
/// </summary>
[Serializable]
abstract class BindClose
{
public void close()
{
string name = this.GetType().Name;
using (FileStream fileStream = new FileStream(name, FileMode.OpenOrCreate))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, this);
}
}
public void load()
{
string name = this.GetType().Name;
using (FileStream fileStream = new FileStream(name, FileMode.OpenOrCreate))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
if (fileStream.Length > 0)
{
object o = binaryFormatter.Deserialize(fileStream);
LoadData(o);
}
}
}
abstract protected void LoadData(object o);
}
}
代码补充,工程中只添加一个lable1
4.运行结果