简体   繁体   中英

Memory Management of UnManaged Objects

I have one query regarding release of unmanaged objects. As unmanaged objects are not directly under control of CLR so CLR can't release it directly and for that we call dispose command but if we didn't use dispose command in our application for that unmanaged object then how resource occupied by that objects will release .

For Ex. If in C# code I am using connection objects as

try
{
    string strConnectionString = "";
    strConnectionString = "Server=FTSPROD\\FTS_PROD;Database=tdps_uat;User ID=txnapp;password=txnapp;Min Pool Size=5;Max Pool Size=10000;";
    for (int i = 0; i < 10000; i++)
    {              
        SqlConnection cnUpdateTransaction;                    
        cnUpdateTransaction = new SqlConnection(strConnectionString);
        cnUpdateTransaction.Open();
        cnUpdateTransaction.
        //cnUpdateTransaction.Close();
    }
}
catch (Exception Ex)
{

}

Here i am opening 10000 instances of connection objects and just leaving it for garbage collection. Now as they are unmanaged objects and i am not calling close or dispose then finally how this objects will be released. Whether operating system will do something for this and when. Please share your with some document link for this issue.

When implementing IDisposable and the class has unmanaged resources you should implement a Finalizer that calls the Dispose method. That way if the user of the class fails to call Dispose unmanaged resources will (eventually) be released when the GC runs. See Implement IDisposable correctly for a good example.

If the object contains references to unmanaged resources and does not contain a finalizer and Dipose is not called then that memory will not be reclaimed automatically. Basically, there is a memory leak. The memory won't be reclaimed until the process is shut down. See Identify And Prevent Memory Leaks In Managed Code for some interesting reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM