首页 > 其他 > 详细

CSharp - Memory leaks problem detection and solution

时间:2015-03-02 23:57:10      阅读:534      评论:0      收藏:0      [点我收藏+]

/* By Dylan SUN*/

Out of memory exception happens when server doesn’t have enough memory to run the application.

This often happens when you are dealing with external resources, such as consuming Interop libraries, treating files, streams, etc.

Memory is a limited resource, it’s easy to be run out of. So, you should be careful when you are working with external resources in your application development.

There are some good memory profilers in the market.
I’ve listed two profilers I’ve used. They are both very easy to use. You can even try them for a limited period.

  1. DotTrace
  2. Ants Memory Profiler

Here are some screenshots of one snapshot in Ants memory profiler.

You could see the memory usage progress with time.
技术分享

You could easily see the memory usage with Heap generation 1, generation 2, Large object heap, Unused memory allocated to .NET, Unmanaged memories.

技术分享

Then you could investigate which instance of class is used, how much times it’s been used, how many memory it has occupied, etc.

技术分享

The best practice to consume an external data source is using “using” statement. Everything you get in external services will be disposed.

using (var service = _serviceAdapter.Configure())
{
    var data = _serviceAdapter.RetrieveData(parameters);
}

If you need to use the retrieved data in several places in your application. You can convert it to a DTO object, so the code becomes managed.

DataDto dataDto = new DataDto();
using (var service = _serviceAdapter.Configure())
{
    var data = _serviceAdapter.RetrieveData(parameters);
    dtoData = ConvertToDto(data);
}

In this way you can use dtoData wherever you like.
After the object’s usage, the data will be collected by GC later.

I hope you find this articles helpful!

CSharp - Memory leaks problem detection and solution

原文:http://blog.csdn.net/garcon1986/article/details/44022223

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!