diff ServerMonitor/Objects/ServerMonitor.cs @ 36:10e60b05c7ec

Fix memory leak each time a check was executed.
author Brad Greco <brad@bgreco.net>
date Sun, 15 Sep 2019 20:48:55 -0400
parents 2ffb0bda7705
children 8ab98a803d39
line wrap: on
line diff
--- a/ServerMonitor/Objects/ServerMonitor.cs	Sat Jul 13 12:18:21 2019 -0400
+++ b/ServerMonitor/Objects/ServerMonitor.cs	Sun Sep 15 20:48:55 2019 -0400
@@ -35,6 +35,8 @@
         // A check task begins by sleeping until the next scheduled execution time,
         // then executes.
         private Dictionary<Task<CheckResult>, int> tasks;
+        // XML serializer that can handle servers and all check types.
+        private XmlSerializer xmlSerializer;
         private ServerSummaryForm mainForm;
         private WaveOut waveOut = new WaveOut();
         MediaFoundationReader mediaReader;
@@ -63,6 +65,7 @@
             configFileDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ServerMonitor");
             ConfigFile = Path.Combine(configFileDir, "servers.xml");
             logger = new Logger(Path.Combine(configFileDir, "monitor.log"));
+            xmlSerializer = new XmlSerializer(typeof(List<Server>), Check.CheckTypes);
         }
 
         /// <summary>Registers a new server with the server monitor.</summary>
@@ -99,9 +102,8 @@
             try
             {
                 reader = new StreamReader(ConfigFile);
-                XmlSerializer serializer = CreateXmlSerializer();
                 Servers.Clear();
-                Servers.AddRange((List<Server>)serializer.Deserialize(reader));
+                Servers.AddRange((List<Server>)xmlSerializer.Deserialize(reader));
                 // Do some more set-up now that the servers and checks have been loaded.
                 foreach (Server server in Servers)
                 {
@@ -169,7 +171,6 @@
         {
             GenerateIds();
             TextWriter writer = null;
-            XmlSerializer serializer = null;
             try
             {
                 // Make a backup first in case something goes wrong in the middle of writing.
@@ -179,16 +180,14 @@
             try
             {
                 writer = new StreamWriter(ConfigFile);
-                serializer = CreateXmlSerializer();
-                serializer.Serialize(writer, Servers);
+                xmlSerializer.Serialize(writer, Servers);
             }
             catch (DirectoryNotFoundException)
             {
                 // If the directory does not exist, create it and try again.
                 Directory.CreateDirectory(configFileDir);
                 writer = new StreamWriter(ConfigFile);
-                serializer = CreateXmlSerializer();
-                serializer.Serialize(writer, Servers);
+                xmlSerializer.Serialize(writer, Servers);
             }
             finally
             {