I need to save state of a complex C# object every 5 mins.
I am using this basic approach below. I found a "fast" object copy from link lower down.
If I comment out the "Task" part of WriteToBinaryFileTask, leaving only the Copy, then process takes 160ms. This is too long for my needs. The object is likely to update every few milliseconds. I need to take a copy as I cannot lock the actual object whilst writing to disk as that takes 1500ms.
What alternatives might I try to take a snap of the state of my object. I really need to get time down to 10ms.
private void SaveState()
{
Stopwatch sw = new Stopwatch();
sw.Start();
UtilsBinarySerialization.WriteToBinaryFileTask<int>(StatePath("PreviousSignalMainLogic"), PreviousSignalMainLogic);
sw.Stop();
Console.WriteLine("Secs: " + sw.ElapsedMilliseconds);
}
public static void WriteToBinaryFileTask<T>(string filePath, T objectToWrite, bool append = false)
{
T objectCopy = ObjectExtensions.Copy(objectToWrite);
Task taskA = new Task(() =>
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectCopy);
}
}
);
taskA.Start();
}
https://github.com/Burtsev-Alexey/net-object-deep-copy/blob/master/ObjectExtensions.cs