How the memory has been allocated and released?How do I calculate someone's age in C#?How do I enumerate an enum in C#?How to measure actual memory usage of an application or process?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?Does CLR release memory from COM objects?How do I remedy the “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning?How do I discover memory usage of my application in Android?Memory Leak questionsWhat is a NullReferenceException, and how do I fix it?Creating a memory leak with Java
Page contents aligning weirdly in LaTeX/Overleaf
On what legal basis did the UK remove the 'European Union' from its passport?
Setting the major mode of a new buffer interactively
Why in a Ethernet LAN, a packet sniffer can obtain all packets sent over the LAN?
What happens if a creature that would fight isn't on the battlefield anymore?
What is Plautus’s pun about frustum and frustrum?
Should these notes be played as a chord or one after another?
What are the components of a legend (in the sense of a tale, not a figure legend)?
Who was this character from the Tomb of Annihilation adventure before they became a monster?
Word for being out at night during curfew
How does noise-cancellation work in Mac laptops?
Why was Thor doubtful about his worthiness to Mjolnir?
Early arrival in Australia, early hotel check in not available
Drawing lines to nearest point
How to make a language evolve quickly?
Is the schwa sound consistent?
How can a Lich look like a human without magic?
What stroke width Instagram is using for its icons and how to get same results?
How can dragons propel their breath attacks to a long distance
Why was castling bad for white in this game, and engine strongly prefered trading queens?
Is taking modulus on both sides of an equation valid?
Was there ever any real use for a 6800-based Apple I?
Why was Endgame Thanos so different than Infinity War Thanos?
Smallest Guaranteed hash collision cycle length
How the memory has been allocated and released?
How do I calculate someone's age in C#?How do I enumerate an enum in C#?How to measure actual memory usage of an application or process?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?Does CLR release memory from COM objects?How do I remedy the “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning?How do I discover memory usage of my application in Android?Memory Leak questionsWhat is a NullReferenceException, and how do I fix it?Creating a memory leak with Java
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am playing around with IDisposable interface and GC and there is something which i cannot understand.
So we have the following class:
public class DatabaseState : IDisposable
protected SqlConnection _connection;
public virtual string GetDate()
if (_disposed)
throw new ObjectDisposedException("DatabaseState");
if (_connection == null)
var connectionString = ConfigurationManager.ConnectionStrings["master"];
_connection = new SqlConnection(connectionString.ConnectionString);
_connection.Open();
using (var command = _connection.CreateCommand())
command.CommandText = "SELECT getdate()";
return command.ExecuteScalar().ToString();
private bool _disposed;
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
protected virtual void Dispose(bool disposing)
if (_disposed)
return;
if (disposing)
if (_connection != null)
_connection.Dispose();
_connection = null;
_disposed = true;
As you can see the class is pretty simple (it only gets current date).
In the Main i have the following code:
class Program
static void Main(string[] args)
Console.WriteLine("'g' to Get Date; 'gc' to Garbage Collect; 'x' to Exit");
var command = "";
while (command != "x")
command = Console.ReadLine();
switch (command)
case "g":
GetDate();
break;
case "gc":
GC.Collect();
break;
private static void GetDate()
using (var databaseState = new DatabaseState())
//var databaseState = new DatabaseState();
Console.WriteLine(databaseState.GetDate());
The first experiment is when i use IDisposable with using (I have used VS build in Diagnostic Tools.)
Look at the following snapshots:
The number represent snapshot ID.
- When I started application. As you can see we have allocated only 29.38 KB.
- When I entered "g" we have allocated 245.70KB which is normal. We have opened a connection, handshake and etc.
- When I entered "g" for the second time we have allocated only 0.55 KB which also should be normal. I checked what kind of object type we have created: Hashtable, Microsoft.Win32.SafeHandles.SafeFileMappingHandle,SectionRecord and etc. I am not familiar with these object types and I think that there are related somehow with CLR.
From now on the strange things happened for me.
4, 5,6,7 I did the same i pressed "g". As you can see we haven't allocated any memory. And this is my first question Why?.
I pressed "gc" which force GC.Collect(). At that point i was surprised. We haven't released any memory. As I know GC.Collect() released the memory from all generations. The second question Why GC hasn't released any memory at this point ?
I pressed "g" again. The same thing as in snapshots 4, 5, 6 and 7. We haven't allocated any memory. Why?
10, 11 Randomly created snapshots.
This is also something interesting. I haven't done any actions and something has allocated 2.4 KB memory. Again i checked what kind of object types we have created: ContextCallback, Microsoft.Win32.SafeHandles.SafeFileMappingHandle, AppDomainPauseManager, ThreadPoolWorkQueue. And again I am not familiar with these types but I think that there are related to CLR.
The same as 12. I haven't done any actions for a while but this time we released 20.66 KB memory. Why?
To summarize:
By my understanding the IDisposable and GC should work in a little different way.
The first time when I instantiate DatabaseState I should open connection, handshake and etc. Because of that we will allocate more memory.
Because of the fact that we use DatabaseState instance in using statement we will release these unmanaged resources. The next time when I use instance of DatabaseState I should allocate some memory (but as I saw from the snapshots 4,5,6,7 and 9 I didn't allocate any memory) only for the instance because the connection, handshake has already been done.
I am missing something but i don't know what and where.
Regards
.net memory garbage-collection clr idisposable
add a comment |
I am playing around with IDisposable interface and GC and there is something which i cannot understand.
So we have the following class:
public class DatabaseState : IDisposable
protected SqlConnection _connection;
public virtual string GetDate()
if (_disposed)
throw new ObjectDisposedException("DatabaseState");
if (_connection == null)
var connectionString = ConfigurationManager.ConnectionStrings["master"];
_connection = new SqlConnection(connectionString.ConnectionString);
_connection.Open();
using (var command = _connection.CreateCommand())
command.CommandText = "SELECT getdate()";
return command.ExecuteScalar().ToString();
private bool _disposed;
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
protected virtual void Dispose(bool disposing)
if (_disposed)
return;
if (disposing)
if (_connection != null)
_connection.Dispose();
_connection = null;
_disposed = true;
As you can see the class is pretty simple (it only gets current date).
In the Main i have the following code:
class Program
static void Main(string[] args)
Console.WriteLine("'g' to Get Date; 'gc' to Garbage Collect; 'x' to Exit");
var command = "";
while (command != "x")
command = Console.ReadLine();
switch (command)
case "g":
GetDate();
break;
case "gc":
GC.Collect();
break;
private static void GetDate()
using (var databaseState = new DatabaseState())
//var databaseState = new DatabaseState();
Console.WriteLine(databaseState.GetDate());
The first experiment is when i use IDisposable with using (I have used VS build in Diagnostic Tools.)
Look at the following snapshots:
The number represent snapshot ID.
- When I started application. As you can see we have allocated only 29.38 KB.
- When I entered "g" we have allocated 245.70KB which is normal. We have opened a connection, handshake and etc.
- When I entered "g" for the second time we have allocated only 0.55 KB which also should be normal. I checked what kind of object type we have created: Hashtable, Microsoft.Win32.SafeHandles.SafeFileMappingHandle,SectionRecord and etc. I am not familiar with these object types and I think that there are related somehow with CLR.
From now on the strange things happened for me.
4, 5,6,7 I did the same i pressed "g". As you can see we haven't allocated any memory. And this is my first question Why?.
I pressed "gc" which force GC.Collect(). At that point i was surprised. We haven't released any memory. As I know GC.Collect() released the memory from all generations. The second question Why GC hasn't released any memory at this point ?
I pressed "g" again. The same thing as in snapshots 4, 5, 6 and 7. We haven't allocated any memory. Why?
10, 11 Randomly created snapshots.
This is also something interesting. I haven't done any actions and something has allocated 2.4 KB memory. Again i checked what kind of object types we have created: ContextCallback, Microsoft.Win32.SafeHandles.SafeFileMappingHandle, AppDomainPauseManager, ThreadPoolWorkQueue. And again I am not familiar with these types but I think that there are related to CLR.
The same as 12. I haven't done any actions for a while but this time we released 20.66 KB memory. Why?
To summarize:
By my understanding the IDisposable and GC should work in a little different way.
The first time when I instantiate DatabaseState I should open connection, handshake and etc. Because of that we will allocate more memory.
Because of the fact that we use DatabaseState instance in using statement we will release these unmanaged resources. The next time when I use instance of DatabaseState I should allocate some memory (but as I saw from the snapshots 4,5,6,7 and 9 I didn't allocate any memory) only for the instance because the connection, handshake has already been done.
I am missing something but i don't know what and where.
Regards
.net memory garbage-collection clr idisposable
If I am not mistaken there is an internal cache of Sqlconnections. In effect only the first call will do the expensive things. Object reuse is pretty common to solve gc issues.
– Alois Kraus
Mar 23 at 12:51
From IDisposable: "The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur." Note the second sentence. What you're most likely seeing is .Net holding on to memory because it thinks you might need it again in the near future. If the system needs memory, then .Net will release whatever it can back to the OS. This is regular behavior for any .Net program...
– Idle_Mind
Mar 23 at 14:43
@Idle_Mind make sense. Do you know some articles/books where I can read in details what actually happens ?
– chunk1ty
Mar 25 at 8:22
Sure, Garbage Collection has links to articles with more details than you'll probably ever need.
– Idle_Mind
Mar 25 at 13:27
add a comment |
I am playing around with IDisposable interface and GC and there is something which i cannot understand.
So we have the following class:
public class DatabaseState : IDisposable
protected SqlConnection _connection;
public virtual string GetDate()
if (_disposed)
throw new ObjectDisposedException("DatabaseState");
if (_connection == null)
var connectionString = ConfigurationManager.ConnectionStrings["master"];
_connection = new SqlConnection(connectionString.ConnectionString);
_connection.Open();
using (var command = _connection.CreateCommand())
command.CommandText = "SELECT getdate()";
return command.ExecuteScalar().ToString();
private bool _disposed;
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
protected virtual void Dispose(bool disposing)
if (_disposed)
return;
if (disposing)
if (_connection != null)
_connection.Dispose();
_connection = null;
_disposed = true;
As you can see the class is pretty simple (it only gets current date).
In the Main i have the following code:
class Program
static void Main(string[] args)
Console.WriteLine("'g' to Get Date; 'gc' to Garbage Collect; 'x' to Exit");
var command = "";
while (command != "x")
command = Console.ReadLine();
switch (command)
case "g":
GetDate();
break;
case "gc":
GC.Collect();
break;
private static void GetDate()
using (var databaseState = new DatabaseState())
//var databaseState = new DatabaseState();
Console.WriteLine(databaseState.GetDate());
The first experiment is when i use IDisposable with using (I have used VS build in Diagnostic Tools.)
Look at the following snapshots:
The number represent snapshot ID.
- When I started application. As you can see we have allocated only 29.38 KB.
- When I entered "g" we have allocated 245.70KB which is normal. We have opened a connection, handshake and etc.
- When I entered "g" for the second time we have allocated only 0.55 KB which also should be normal. I checked what kind of object type we have created: Hashtable, Microsoft.Win32.SafeHandles.SafeFileMappingHandle,SectionRecord and etc. I am not familiar with these object types and I think that there are related somehow with CLR.
From now on the strange things happened for me.
4, 5,6,7 I did the same i pressed "g". As you can see we haven't allocated any memory. And this is my first question Why?.
I pressed "gc" which force GC.Collect(). At that point i was surprised. We haven't released any memory. As I know GC.Collect() released the memory from all generations. The second question Why GC hasn't released any memory at this point ?
I pressed "g" again. The same thing as in snapshots 4, 5, 6 and 7. We haven't allocated any memory. Why?
10, 11 Randomly created snapshots.
This is also something interesting. I haven't done any actions and something has allocated 2.4 KB memory. Again i checked what kind of object types we have created: ContextCallback, Microsoft.Win32.SafeHandles.SafeFileMappingHandle, AppDomainPauseManager, ThreadPoolWorkQueue. And again I am not familiar with these types but I think that there are related to CLR.
The same as 12. I haven't done any actions for a while but this time we released 20.66 KB memory. Why?
To summarize:
By my understanding the IDisposable and GC should work in a little different way.
The first time when I instantiate DatabaseState I should open connection, handshake and etc. Because of that we will allocate more memory.
Because of the fact that we use DatabaseState instance in using statement we will release these unmanaged resources. The next time when I use instance of DatabaseState I should allocate some memory (but as I saw from the snapshots 4,5,6,7 and 9 I didn't allocate any memory) only for the instance because the connection, handshake has already been done.
I am missing something but i don't know what and where.
Regards
.net memory garbage-collection clr idisposable
I am playing around with IDisposable interface and GC and there is something which i cannot understand.
So we have the following class:
public class DatabaseState : IDisposable
protected SqlConnection _connection;
public virtual string GetDate()
if (_disposed)
throw new ObjectDisposedException("DatabaseState");
if (_connection == null)
var connectionString = ConfigurationManager.ConnectionStrings["master"];
_connection = new SqlConnection(connectionString.ConnectionString);
_connection.Open();
using (var command = _connection.CreateCommand())
command.CommandText = "SELECT getdate()";
return command.ExecuteScalar().ToString();
private bool _disposed;
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
protected virtual void Dispose(bool disposing)
if (_disposed)
return;
if (disposing)
if (_connection != null)
_connection.Dispose();
_connection = null;
_disposed = true;
As you can see the class is pretty simple (it only gets current date).
In the Main i have the following code:
class Program
static void Main(string[] args)
Console.WriteLine("'g' to Get Date; 'gc' to Garbage Collect; 'x' to Exit");
var command = "";
while (command != "x")
command = Console.ReadLine();
switch (command)
case "g":
GetDate();
break;
case "gc":
GC.Collect();
break;
private static void GetDate()
using (var databaseState = new DatabaseState())
//var databaseState = new DatabaseState();
Console.WriteLine(databaseState.GetDate());
The first experiment is when i use IDisposable with using (I have used VS build in Diagnostic Tools.)
Look at the following snapshots:
The number represent snapshot ID.
- When I started application. As you can see we have allocated only 29.38 KB.
- When I entered "g" we have allocated 245.70KB which is normal. We have opened a connection, handshake and etc.
- When I entered "g" for the second time we have allocated only 0.55 KB which also should be normal. I checked what kind of object type we have created: Hashtable, Microsoft.Win32.SafeHandles.SafeFileMappingHandle,SectionRecord and etc. I am not familiar with these object types and I think that there are related somehow with CLR.
From now on the strange things happened for me.
4, 5,6,7 I did the same i pressed "g". As you can see we haven't allocated any memory. And this is my first question Why?.
I pressed "gc" which force GC.Collect(). At that point i was surprised. We haven't released any memory. As I know GC.Collect() released the memory from all generations. The second question Why GC hasn't released any memory at this point ?
I pressed "g" again. The same thing as in snapshots 4, 5, 6 and 7. We haven't allocated any memory. Why?
10, 11 Randomly created snapshots.
This is also something interesting. I haven't done any actions and something has allocated 2.4 KB memory. Again i checked what kind of object types we have created: ContextCallback, Microsoft.Win32.SafeHandles.SafeFileMappingHandle, AppDomainPauseManager, ThreadPoolWorkQueue. And again I am not familiar with these types but I think that there are related to CLR.
The same as 12. I haven't done any actions for a while but this time we released 20.66 KB memory. Why?
To summarize:
By my understanding the IDisposable and GC should work in a little different way.
The first time when I instantiate DatabaseState I should open connection, handshake and etc. Because of that we will allocate more memory.
Because of the fact that we use DatabaseState instance in using statement we will release these unmanaged resources. The next time when I use instance of DatabaseState I should allocate some memory (but as I saw from the snapshots 4,5,6,7 and 9 I didn't allocate any memory) only for the instance because the connection, handshake has already been done.
I am missing something but i don't know what and where.
Regards
.net memory garbage-collection clr idisposable
.net memory garbage-collection clr idisposable
asked Mar 23 at 12:02
chunk1tychunk1ty
4016
4016
If I am not mistaken there is an internal cache of Sqlconnections. In effect only the first call will do the expensive things. Object reuse is pretty common to solve gc issues.
– Alois Kraus
Mar 23 at 12:51
From IDisposable: "The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur." Note the second sentence. What you're most likely seeing is .Net holding on to memory because it thinks you might need it again in the near future. If the system needs memory, then .Net will release whatever it can back to the OS. This is regular behavior for any .Net program...
– Idle_Mind
Mar 23 at 14:43
@Idle_Mind make sense. Do you know some articles/books where I can read in details what actually happens ?
– chunk1ty
Mar 25 at 8:22
Sure, Garbage Collection has links to articles with more details than you'll probably ever need.
– Idle_Mind
Mar 25 at 13:27
add a comment |
If I am not mistaken there is an internal cache of Sqlconnections. In effect only the first call will do the expensive things. Object reuse is pretty common to solve gc issues.
– Alois Kraus
Mar 23 at 12:51
From IDisposable: "The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur." Note the second sentence. What you're most likely seeing is .Net holding on to memory because it thinks you might need it again in the near future. If the system needs memory, then .Net will release whatever it can back to the OS. This is regular behavior for any .Net program...
– Idle_Mind
Mar 23 at 14:43
@Idle_Mind make sense. Do you know some articles/books where I can read in details what actually happens ?
– chunk1ty
Mar 25 at 8:22
Sure, Garbage Collection has links to articles with more details than you'll probably ever need.
– Idle_Mind
Mar 25 at 13:27
If I am not mistaken there is an internal cache of Sqlconnections. In effect only the first call will do the expensive things. Object reuse is pretty common to solve gc issues.
– Alois Kraus
Mar 23 at 12:51
If I am not mistaken there is an internal cache of Sqlconnections. In effect only the first call will do the expensive things. Object reuse is pretty common to solve gc issues.
– Alois Kraus
Mar 23 at 12:51
From IDisposable: "The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur." Note the second sentence. What you're most likely seeing is .Net holding on to memory because it thinks you might need it again in the near future. If the system needs memory, then .Net will release whatever it can back to the OS. This is regular behavior for any .Net program...
– Idle_Mind
Mar 23 at 14:43
From IDisposable: "The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur." Note the second sentence. What you're most likely seeing is .Net holding on to memory because it thinks you might need it again in the near future. If the system needs memory, then .Net will release whatever it can back to the OS. This is regular behavior for any .Net program...
– Idle_Mind
Mar 23 at 14:43
@Idle_Mind make sense. Do you know some articles/books where I can read in details what actually happens ?
– chunk1ty
Mar 25 at 8:22
@Idle_Mind make sense. Do you know some articles/books where I can read in details what actually happens ?
– chunk1ty
Mar 25 at 8:22
Sure, Garbage Collection has links to articles with more details than you'll probably ever need.
– Idle_Mind
Mar 25 at 13:27
Sure, Garbage Collection has links to articles with more details than you'll probably ever need.
– Idle_Mind
Mar 25 at 13:27
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55313531%2fhow-the-memory-has-been-allocated-and-released%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55313531%2fhow-the-memory-has-been-allocated-and-released%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
If I am not mistaken there is an internal cache of Sqlconnections. In effect only the first call will do the expensive things. Object reuse is pretty common to solve gc issues.
– Alois Kraus
Mar 23 at 12:51
From IDisposable: "The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur." Note the second sentence. What you're most likely seeing is .Net holding on to memory because it thinks you might need it again in the near future. If the system needs memory, then .Net will release whatever it can back to the OS. This is regular behavior for any .Net program...
– Idle_Mind
Mar 23 at 14:43
@Idle_Mind make sense. Do you know some articles/books where I can read in details what actually happens ?
– chunk1ty
Mar 25 at 8:22
Sure, Garbage Collection has links to articles with more details than you'll probably ever need.
– Idle_Mind
Mar 25 at 13:27