Added a workaround for the "You must keep the stream open for the lifetime of the Image." problem of the Image.FromStream method. This also reduced the overall memory usage (private working set).
authormoel.mich
Tue, 25 May 2010 18:57:28 +0000
changeset 12776aaf45a01c7
parent 126 2354fdb91ac4
child 128 cea5477b4d72
Added a workaround for the "You must keep the stream open for the lifetime of the Image." problem of the Image.FromStream method. This also reduced the overall memory usage (private working set).
Utilities/EmbeddedResources.cs
     1.1 --- a/Utilities/EmbeddedResources.cs	Mon May 24 15:27:46 2010 +0000
     1.2 +++ b/Utilities/EmbeddedResources.cs	Tue May 25 18:57:28 2010 +0000
     1.3 @@ -38,6 +38,7 @@
     1.4  using System;
     1.5  using System.Collections.Generic;
     1.6  using System.Drawing;
     1.7 +using System.IO;
     1.8  using System.Reflection;
     1.9  
    1.10  namespace OpenHardwareMonitor.Utilities {
    1.11 @@ -49,10 +50,23 @@
    1.12        string[] names = 
    1.13          Assembly.GetExecutingAssembly().GetManifestResourceNames();
    1.14        for (int i = 0; i < names.Length; i++) {
    1.15 -        if (names[i].Replace('\\', '.') == name)
    1.16 -          return new Bitmap(Assembly.GetExecutingAssembly().
    1.17 -        GetManifestResourceStream(names[i]));
    1.18 -      }
    1.19 +        if (names[i].Replace('\\', '.') == name) {
    1.20 +          using (Stream stream = Assembly.GetExecutingAssembly().
    1.21 +            GetManifestResourceStream(names[i])) {
    1.22 +
    1.23 +            // "You must keep the stream open for the lifetime of the Image."
    1.24 +            Image image = Image.FromStream(stream);
    1.25 +
    1.26 +            // so we just create a copy of the image 
    1.27 +            Bitmap bitmap = new Bitmap(image);
    1.28 +
    1.29 +            // and dispose it right here
    1.30 +            image.Dispose();
    1.31 +
    1.32 +            return bitmap;
    1.33 +          }
    1.34 +        }
    1.35 +      } 
    1.36  
    1.37        return new Bitmap(1, 1);    
    1.38      }
    1.39 @@ -63,10 +77,13 @@
    1.40        string[] names =
    1.41          Assembly.GetExecutingAssembly().GetManifestResourceNames();
    1.42        for (int i = 0; i < names.Length; i++) {
    1.43 -        if (names[i].Replace('\\', '.') == name)
    1.44 -          return new Icon(Assembly.GetExecutingAssembly().
    1.45 -        GetManifestResourceStream(names[i]));
    1.46 -      }
    1.47 +        if (names[i].Replace('\\', '.') == name) {
    1.48 +          using (Stream stream = Assembly.GetExecutingAssembly().
    1.49 +            GetManifestResourceStream(names[i])) {
    1.50 +            return new Icon(stream);
    1.51 +          }
    1.52 +        }          
    1.53 +      } 
    1.54  
    1.55        return null;
    1.56      }