Not enough memory

I have a code here

   private void Run()
    {
        MyClass c = new MyClass();
        c.Load(somepath1);
        using (StreamReader sr = new StreamReader(filepath))
        {
            string line = string.Empty;
            while ((line = sr.ReadLine()) != null)
            {
                using (Bitmap B = new Bitmap(line))
                {
                    Point p = SomeMethod(ref c, new Point());
                    using (MemoryStream ms = new MemoryStream())
                    {
                        B.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                        using (Bitmap T = new Bitmap(new Bitmap(Image.FromStream(ms))))
                        using (Graphics g = Graphics.FromImage(T))
                        {
                            g.DrawEllipse(new Pen(Brushes.Red, 4), p.X - 5, p.Y - 5, 10, 10);
                            FileInfo fi = new FileInfo(somepath2);
                            T.Save(Path.Combine(somepath3, fi.Name));
                        }
                    }
                }
            }
        }
    } 

and SomeMethod function:

    Point SomeMethod(ref MyClass c, Point mid)
    {
        float[] Mat = new float[9];
        Point p;

        c.Method1(Mat);
        c.Method2(Mat, out p);

        return p;
    }

MyClass:

public class MyClass
{
    public void Method1(float[] Mat, out Point point)
    {
        //calculation point from values in Mat
    }

    public void Method2(float[] Mat)
    {
        //Do some Operation in Mat
    }

    public void Load(string FileName)
    {
        //Do Some Data Loading From a small file about 400 byte
    }
}

StreamReader sr Opens a file in the path to a file that contains about 400 lines of images, I read them and draw on them, based on my calculations, I did not use any external library or any unsafe code. The question is, why do I run out of memory?

------------- EDIT --------------------

when the program starts, it uses about 20 MB of memory after the call. Start the memory usage launch, if I ran it for about 200 images, the memory costs about 1.7 GB, and the "Start" function has finished working and the memory usage will return to 20 MB

------------ ------------ EDIT Bitmap B MemoryStream , . : ? , .

---------- ----------------

:

System.OutOfMemoryException was unhandled
  Message=Out of memory.
  Source=System.Drawing
  StackTrace:
       at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
       at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
       at System.Drawing.Bitmap..ctor(Image original, Int32 width, Int32 height)
       at System.Drawing.Bitmap..ctor(Image original)
       at WindowsFormsApplication1.Form1.buttonrun1_Click(Object sender, EventArgs e) in C:\Users\hamidp\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 115
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsFormsApplication1.Program.Main() in C:\Users\hamidp\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 17
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

, :

using (Bitmap T = new Bitmap(new Bitmap(Image.FromStream(ms))))

------------------- EDIT -----------------------

GC.Collect();

while ((line = sr.ReadLine()) != null)

.

+5
6

GC.Collect() GC.WaitForPendingFinalizers(), .

0

, , , .

:

using (Bitmap T = new Bitmap(new Bitmap(Image.FromStream(ms))))

FromStream , . Bitmap , . Bitmap, .

, using , , - , , .

, :

using (Bitmap T = (Bitmap)Image.FromStream(ms))

:

g.DrawEllipse(new Pen(Brushes.Red, 4), p.X - 5, p.Y - 5, 10, 10);

Pen, . :

Using (Pen red = new Pen(Brushes.Red, 4)) {
  g.DrawEllipse(red, p.X - 5, p.Y - 5, 10, 10);
}
+14

, 32 ANY CPU.

64-, 2GB 32- .

+1

, , - .

, , 100 , 2 + ( + ).

, , , 10 .

+1

4 . Bitmap B, , , T , , Graphics g. ?

Bitmap B B.Save, use, . , , . , B.Save() B, .

. B, B ( SomeMethod ), . ? T B.

Bitmap ( Bitmap (Image.FromStream(...)))? .

():

while ((line = sr.ReadLine()) != null) 
{ 
    Bitmap T = null;
    try
    {
        MemoryStream ms = new MemoryStream()) 
        try
        { 
            Bitmap B = new Bitmap(line);
            try
            { 
                Point p = SomeMethod(ref c, new Point()); 
                B.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            }
            finally 
            {
                B.Dispose();
            }

            T = new Bitmap(Image.FromStream(ms));
        }
        finally
        {
            m.Dispose();
        }

        using (Graphics g = Graphics.FromImage(T)) 
        { 
            g.DrawEllipse(new Pen(Brushes.Red, 4), p.X - 5, p.Y - 5, 10, 10); 
            FileInfo fi = new FileInfo(somepath2); 
            T.Save(Path.Combine(somepath3, fi.Name)); 
        }
    }
    finally
    {
        if (T != null)
        {
            T.Dispose();
        } 
    }
} 

, Bitmap B memystream M. , , GC , GC . GC , , , - live ( ), , , .

, - GDI- , .NET GC , . , GC, , Bitmap. , , GDI.

, , . , , , . , try..finally , IMO.

+1
source

using GC.Collect()or is GC.WaitForPendingFinalizers()not the right way to fix this problem. You are getting this error because you still have a Bitmap object. Therefore, you must delete it.

try
{
    IntPtr intPtrHBitmap = IntPtr.Zero; 
    BitmapSource _Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(intPtrHBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    DeleteObject(intPtrHBitmap);
    _Source = null;
}

Paste the following code at the class level.

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject); 
0
source

All Articles