473,651 Members | 2,917 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory in windows forms

Hi,
Consider the following situation
I have the following routine running repeatedly (curControl is a UserControl
with say 1000 textboxes and a big array of strings):

Public Sub AddControl(ByVa l ctlName As String)
If Not IsNothing(curCo ntrol) Then
Me.Controls.Rem ove(curControl)
End If

Dim assemb As [Assembly] = [Assembly].Load("MyContro lAssembly")
curControl = CType(assemb.Cr eateInstance(ct lName), UserControl)
curControl.Loca tion = New Point(150, 20)
Me.Controls.Add (curControl)
End Sub

Now, running this Sub over and over, the memory stays more or less the same.
That is to say, it goes up a litte bit - maybe 4-20K, but nothing huge.

Now, consider this version:

Public Sub AddControl(ByVa l ctlName As String)
If Not IsNothing(curCo ntrol) Then
curControl.Disp ose()
End If

Dim assemb As [Assembly] = [Assembly].Load("MyContro lAssembly")
curControl = CType(assemb.Cr eateInstance(ct lName), UserControl)
curControl.Loca tion = New Point(150, 20)
End Sub

Now, in this version, the control is not being added to the form - it is
just created.

In this case, the memory goes up by about .5 MB every time this code runs.

Now, the questions is, why is it that in the first scenario, the control is
cleaned up properly - but in the second scenario (where Dispose is actually
being closed), it is not. The memory keeps climbing up and up.

Thanks
Jul 21 '05 #1
22 1974
In the second example, you're calling dispose, but you're not removing the
control, so a reference to it remains. You should call
Me.Controls.Rem ove(curControl) then curControl.Disp ose() in both case. It's
not an either/or situation.

Pete

"Marina" <so*****@nospam .com> wrote in message
news:uZ******** ******@TK2MSFTN GP09.phx.gbl...
Hi,
Consider the following situation
I have the following routine running repeatedly (curControl is a UserControl with say 1000 textboxes and a big array of strings):

Public Sub AddControl(ByVa l ctlName As String)
If Not IsNothing(curCo ntrol) Then
Me.Controls.Rem ove(curControl)
End If

Dim assemb As [Assembly] = [Assembly].Load("MyContro lAssembly")
curControl = CType(assemb.Cr eateInstance(ct lName), UserControl)
curControl.Loca tion = New Point(150, 20)
Me.Controls.Add (curControl)
End Sub

Now, running this Sub over and over, the memory stays more or less the same. That is to say, it goes up a litte bit - maybe 4-20K, but nothing huge.

Now, consider this version:

Public Sub AddControl(ByVa l ctlName As String)
If Not IsNothing(curCo ntrol) Then
curControl.Disp ose()
End If

Dim assemb As [Assembly] = [Assembly].Load("MyContro lAssembly")
curControl = CType(assemb.Cr eateInstance(ct lName), UserControl)
curControl.Loca tion = New Point(150, 20)
End Sub

Now, in this version, the control is not being added to the form - it is
just created.

In this case, the memory goes up by about .5 MB every time this code runs.

Now, the questions is, why is it that in the first scenario, the control is cleaned up properly - but in the second scenario (where Dispose is actually being closed), it is not. The memory keeps climbing up and up.

Thanks

Jul 21 '05 #2
I apologize for the misprint. That line that adds the control is actually
commented out in my experiment for test #2.

<pd******@hotma il.com> wrote in message
news:15******** *************** *******@news.me ganetnews.com.. .
In the second example, you're calling dispose, but you're not removing the
control, so a reference to it remains. You should call
Me.Controls.Rem ove(curControl) then curControl.Disp ose() in both case. It's not an either/or situation.

Pete

"Marina" <so*****@nospam .com> wrote in message
news:uZ******** ******@TK2MSFTN GP09.phx.gbl...
Hi,
Consider the following situation
I have the following routine running repeatedly (curControl is a

UserControl
with say 1000 textboxes and a big array of strings):

Public Sub AddControl(ByVa l ctlName As String)
If Not IsNothing(curCo ntrol) Then
Me.Controls.Rem ove(curControl)
End If

Dim assemb As [Assembly] = [Assembly].Load("MyContro lAssembly")
curControl = CType(assemb.Cr eateInstance(ct lName), UserControl)
curControl.Loca tion = New Point(150, 20)
Me.Controls.Add (curControl)
End Sub

Now, running this Sub over and over, the memory stays more or less the

same.
That is to say, it goes up a litte bit - maybe 4-20K, but nothing huge.

Now, consider this version:

Public Sub AddControl(ByVa l ctlName As String)
If Not IsNothing(curCo ntrol) Then
curControl.Disp ose()
End If

Dim assemb As [Assembly] = [Assembly].Load("MyContro lAssembly")
curControl = CType(assemb.Cr eateInstance(ct lName), UserControl)
curControl.Loca tion = New Point(150, 20)
End Sub

Now, in this version, the control is not being added to the form - it is
just created.

In this case, the memory goes up by about .5 MB every time this code runs.
Now, the questions is, why is it that in the first scenario, the control

is
cleaned up properly - but in the second scenario (where Dispose is

actually
being closed), it is not. The memory keeps climbing up and up.

Thanks


Jul 21 '05 #3
Hi Marina,

You got no further answers I see, my thought was that the dispose is maybe
not well done in your usercontrol. However just a gues and therefore such a
late answer.

In your example 1 you set a reference to the control and remove that
reference
In your example 2 you set no reference to the control so there is nothing to
remove

So example 2 should work the same as example 1 even without the dispose.
That would mean in my opinion that in the dispose a reference is set.

However just guessing.

Cor
Jul 21 '05 #4
In the first example, I do not call Dispose at all. I just add the control
so it is visible - and then remove it.
However, the control is cleaned up properly, and its memory released.

In the second version, I tried doing everything the same exact the
add/remove. The memory was now not released properly.

I then tried adding the Dispose, just in case. This didn't help.

The questions is: why is adding/removing the control to the form, somehow
clean up its memory when the control is no longer referenced by anything.
But just creating it, and dereferencing it, does not?

"Cor Ligthert" <no**********@p lanet.nl> wrote in message
news:ut******** ******@tk2msftn gp13.phx.gbl...
Hi Marina,

You got no further answers I see, my thought was that the dispose is maybe
not well done in your usercontrol. However just a gues and therefore such a late answer.

In your example 1 you set a reference to the control and remove that
reference
In your example 2 you set no reference to the control so there is nothing to remove

So example 2 should work the same as example 1 even without the dispose.
That would mean in my opinion that in the dispose a reference is set.

However just guessing.

Cor

Jul 21 '05 #5
Hi Mariane,

I thought that you would have done as you said and that that was your start,
in my opinion is this a typical question for Jon.

It seems as you said that the add and/or the remove are adding/removing
references more than only the reference to the parent.

However why would there be a reference.

I do not like this kind of problems anymore, it is following deep the code
and than reading somewhere else suddenly why this behaviour is.

Cor
Jul 21 '05 #6
Cor Ligthert <no**********@p lanet.nl> wrote:
I thought that you would have done as you said and that that was your start,
in my opinion is this a typical question for Jon.

It seems as you said that the add and/or the remove are adding/removing
references more than only the reference to the parent.

However why would there be a reference.

I do not like this kind of problems anymore, it is following deep the code
and than reading somewhere else suddenly why this behaviour is.


Okay, I'll have a look.

Marina, could you come up with a short but complete example which
demonstrates the problem?

See http://www.pobox.com/~skeet/csharp/complete.html

(Don't worry, you don't need to write it in C# - I just want to be able
to paste your code into an empty text file and compile it from the
command line.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #7
Ok, here is a complete program. First file is the form, second is the
UserControl in question.

Run it and click button1 repeatedly. Memory will keep growing and growing
with every click (500K at a time or so).

Stop it, and run it again. This time click button2 repeatedly. Memory will
grow at first, but remain steady - growing maybe 4-20K at a time - so barely
noticeable.

Thanks for your interest...

Form:

Public Class Form1
Inherits System.Windows. Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeCompo nent()
'Add any initialization after the InitializeCompo nent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Disp ose()
End If
End If
MyBase.Dispose( disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.Componen tModel.IContain er
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Button1 As System.Windows. Forms.Button
Friend WithEvents Button2 As System.Windows. Forms.Button
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub InitializeCompo nent()
Me.Button1 = New System.Windows. Forms.Button
Me.Button2 = New System.Windows. Forms.Button
Me.SuspendLayou t()
'
'Button1
'
Me.Button1.Loca tion = New System.Drawing. Point(24, 24)
Me.Button1.Name = "Button1"
Me.Button1.TabI ndex = 0
Me.Button1.Text = "Button1"
'
'Button2
'
Me.Button2.Loca tion = New System.Drawing. Point(24, 64)
Me.Button2.Name = "Button2"
Me.Button2.TabI ndex = 1
Me.Button2.Text = "Button2"
'
'Form1
'
Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13)
Me.ClientSize = New System.Drawing. Size(552, 598)
Me.Controls.Add (Me.Button2)
Me.Controls.Add (Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout (False)
End Sub
#End Region
Dim curControl As UserControl
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
If Not IsNothing(curCo ntrol) Then
curControl.Disp ose()
End If
curControl = New UserControl1
End Sub
Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button2.Click
If Not IsNothing(curCo ntrol) Then
Controls.Remove (curControl)
End If
curControl = New UserControl1
curControl.Loca tion = New Point(50, 50)
Controls.Add(cu rControl)
End Sub
End Class

UserControl:

Public Class UserControl1
Inherits System.Windows. Forms.UserContr ol
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeCompo nent()
'Add any initialization after the InitializeCompo nent() call
init()
End Sub
'UserControl1 overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Disp ose()
End If
End If
MyBase.Dispose( disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.Componen tModel.IContain er
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub InitializeCompo nent()
'
'UserControl1
'
Me.Name = "UserContro l1"
Me.Size = New System.Drawing. Size(392, 424)
End Sub
#End Region
Dim myData As New ArrayList
Public Sub init()
For i As Integer = 1 To 1000
Dim t As TextBox = New TextBox
t.Location = New Point(0, i * 40)
t.Text = i & "test"
Me.Controls.Add (t)
myData.Add(i & "test")
Next
End Sub
End Class

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Cor Ligthert <no**********@p lanet.nl> wrote:
I thought that you would have done as you said and that that was your start, in my opinion is this a typical question for Jon.

It seems as you said that the add and/or the remove are adding/removing
references more than only the reference to the parent.

However why would there be a reference.

I do not like this kind of problems anymore, it is following deep the code and than reading somewhere else suddenly why this behaviour is.


Okay, I'll have a look.

Marina, could you come up with a short but complete example which
demonstrates the problem?

See http://www.pobox.com/~skeet/csharp/complete.html

(Don't worry, you don't need to write it in C# - I just want to be able
to paste your code into an empty text file and compile it from the
command line.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Jul 21 '05 #8
Hi Marina/Jon,

Can you try this also,

With me it was not the add handler that triggered the cleaning up of the
memory however it seems to me the changing of the form, (or how you want to
say that).

(I added that dispose in button2 proc because otherwise the program went
completly down).

With visible is true the behaviour as described by Marina the same by me,
with visible = false seems the behaviour for Button1 and Button2 the same.
(I used the taskmanager and nothing more).

However maybe I thougth it alone.

Cor
\\\\
Private Sub Button1_Click(B yVal sender As System.Object, _
ByVal e As System.EventArg s) Handles Button1.Click
For i As Integer = 0 To 100
If Not IsNothing(curCo ntrol) Then
curControl.Disp ose()
End If
curControl = New UserControl1
Next
End Sub
Private Sub Button2_Click(B yVal sender As System.Object, _
ByVal e As System.EventArg s) Handles Button2.Click
For i As Integer = 0 To 100
If Not IsNothing(curCo ntrol) Then
Controls.Remove (curControl)
curControl.Disp ose()
End If
curControl = New UserControl1
curControl.Loca tion = New Point(50, 50)
curControl.Visi ble = False 'this to change
Controls.Add(cu rControl)
Next
End Sub
////
Jul 21 '05 #9
"Marina" <so*****@nospam .com> schrieb
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e
As System.EventArg s) Handles Button1.Click
If Not IsNothing(curCo ntrol) Then
curControl.Disp ose()
End If
curControl = New UserControl1
End Sub Private Sub Button2_Click(B yVal sender As System.Object, ByVal e
As System.EventArg s) Handles Button2.Click
If Not IsNothing(curCo ntrol) Then
Controls.Remove (curControl)
End If
curControl = New UserControl1
curControl.Loca tion = New Point(50, 50)
Controls.Add(cu rControl)
End Sub

Maybe it's too simple, but I think the solution is that clicking Button2
uses much more memory because the control is added to the Form. This causes
the garbage collection and memory to be freed. With Button1, you also need
a lot of memory, but not as much as when making the Usercontrol including
1000 textboxes visible as done in Button2_click, so Button1_click consumes
much less memory and consequently GC isn't started.
Simply leave out curControl.disp ose in Button1_click and you will see that
memory is freed earlier. I also suggest to add this to the Usercontrol:

Protected Overrides Sub Finalize()
Debug.WriteLine ("finalize " & Date.Now.TimeOf Day.ToString)
MyBase.Finalize ()
End Sub

In Sub New:
Debug.WriteLine ("Sub New " & Date.Now.TimeOf Day.ToString)

In Sub Dispose:
Debug.WriteLine ("Dispose " & Date.Now.TimeOf Day.ToString)

Now, without curControl.disp ose in Button1_click, pressing Button1 consumes
memory faster and you will see that GC will take place after few clicks
(after 6 here at my machine). Try this also including curControl.disp ose and
you'll see the difference.
In other words:
When calling dispose, less memory is consumed than when not calling dispose.
Consequently GC takes place later and memory is freed later.
When not calling dispose, memory is consumed faster and GC takes place
earlier. Consequently memory is freed earlier.

I'm not 100% sure but I think this can be the explanation.
--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html
Jul 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2402
by: Ray Cassick \(Home\) | last post by:
I have been beating myself up over trying to locate what I thought was a memory leak in MY code but based upon what I have seen I can't be sure that it IS my fault or something strange with DOTNET. Someone here please feel free to enlighten me on this one. The code to reproduce is very simple. Done in VB.NET, One form with a button on it called cmdStart. Here is the code behind the form: Public Class Form1 Inherits...
7
1859
by: fremenusul | last post by:
I know I have been asking LOTS of xml questions and I really apprecaite all the help. Here is my XML file <?xml version="1.0" encoding="utf-8" ?> <products> <!-- Repeat the structure below for each product. --> <product> <id>CP-90, T-32</id>
9
2341
by: Mike P | last post by:
I know everything about reference counting and making sure you don't have large objects lying around. I have also profiled my app with multiple tools. I know about the fact GC collects memory but not necessary give it back to the OS. It seems that .NET win app will only return memory to the OS when the OS is asking for it. But!!! When the OS is asking for it is usually too late, tons of swapping and slow performance.
11
21006
by: Pete Davis | last post by:
I have an app that's dealing with a few hundred bitmap thumbnails. I only instantiate the bitmaps that are visible at a given time and dispose of them if they get scrolled out of view. I've used the .NET memory profiler and I've verified there's no leak in my bitmaps, nor are there any other apparent leaks. So, at a given time, there may be 30 or so bitmaps displayed at a given time. Still, somehow, I'm getting random errors in the...
2
2291
by: Liverpool fan | last post by:
I have a VB .NET windows application that is throwing an intermittent 'out of memory' error. Here is the call stack. Out of memory. at System.Drawing.Graphics.FromHdcInternal(IntPtr hdc) at System.Windows.Forms.DibGraphicsBufferManager.CreateBuffer(IntPtr src, Int32 offsetX, Int32 offsetY, Int32 width, Int32 height) at System.Windows.Forms.DibGraphicsBufferManager.AllocBuffer(Graphics
2
21970
by: Ilkka | last post by:
I have created an C++ application with Windows Forms, ADO and SQL server 2005. Now I need to change something and started debugging the code. Then suddenly I receive an error. "An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." The progran ends on a windows form designer...
1
4080
by: Marc Bartsch | last post by:
Hi, My C# app throws the following exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. From what I read so far I found that the problem can be connected to P/Invoke and that the places at which this exception is thrown might not reflect the actual problem. In my case, the exception is thrown, when I try to minimise my main window to the system...
4
6085
by: SteveHasel | last post by:
I understand that this has come up quite a bit in the forums, and I've looked over a lot of questions and possible solutions and haven't found one that has worked for me yet. I was hoping someone else might have an idea. Here's the full error message: (I underlined what I thought was the most relevant) "System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. ...
6
4486
by: Scott Gravenhorst | last post by:
Windows XP SP3 My application is set to open a SaveFile dialog when an exit is requested. When I click the app's close button, the save dialog opens, but when I click to change the folder, the exception occurs pointing to FileSaveDialog1.ShowDialog(). The exception also indicates some problem with system.drawing.dll. The exception text is: "Attempted to read or write protected memory. This is often an
11
4221
by: dhtml | last post by:
(originally mis-posted on m.p.s.jscript...) I've just closed all windows in Firefox and its using 244MB of memory. I have no idea why. I had GMail open, a page from unicode, the CLJ FAQ. I've noticed that createElement leaks. It's obvious with form controls because the form keeps the control name as a property. Example:
0
8357
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8803
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8581
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5612
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4285
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2701
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1910
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.