内存释放与IDisposable和没有IDisposable [英] Memory release with IDisposable and without IDisposable

查看:202
本文介绍了内存释放与IDisposable和没有IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个大对象,每隔几秒创建一次,然后我不再需要它了。



我在任务中看到经理说,即使我没有ant对象引用,它将需要被收集,公羊的大小上升。



我试图实现IDisposable,然后公羊直接下降。



这是为什么?我不做GC.Collect我只是释放该对象并告诉GC他不需要为我的对象调用终结器?

更新



以下是我在IDIsposable对象中使用的代码:

  public void Dispose()
{
base.Dispose();
Dispoe(true);
GC.SuppressFinalize();
}

private void Dispoe(bool disposing)
{
//这里我释放非托管资源
if(disposing)
{
//在这里我释放所有托管资源


$ b〜MyObject()
{
Dispose(false);
}

在我的大对象中,我做了myObject.Dispose();我不再需要他了。



我的问题不是关于如何实现IDisposable,而不是关于GC代工作的一般。



我只是想知道在这种情况下,我可以如何区分内存大小不同的情况,我会Dispoe到我的对象以及我没有Dispoe我的对象。


你写
我试图实现IDisposable然后公羊直接下落。



重要的是你的工具是做什么的。那里的代码应该清理非托管代码,Windows资源等。

In my app I have a large object that created every few seconds I do with it some job and then I dont need it anymore.

I saw in the task manager that the ram size go up even if I dont have ant reference to the object and it will need to being collected.

I tried to implement IDisposable and then the ram goes down immideitly.

Why is this? I dont did GC.Collect I just release the object and tell to GC that he dont need to call finalizer for my object?

Update

Here is the code I use in my IDIsposable objects:

public void Dispose()
{
  base.Dispose();
  Dispoe(true);
  GC.SuppressFinalize();
}

private void Dispoe(bool disposing)
{
  //here i release unmanaged resources
  if (disposing)
  {
    //here i release all managed resources
  }
}

~MyObject()
{
  Dispose(false);
}

And in my large object I do myObject.Dispose(); after i didnt need him anymore.

My question was not about how to implement IDisposable and not about GC generations work at general.

I just want to know how it is possible the case of difference in the ram size between the case i do Dispoe to my object to case that i dont Dispoe my object.

解决方案

As @Steven pointed out in his comments, IDisposable is something the CLR doesn't care about. By implementing it you simply tell consumers of your object to call its Dispose method when object no longer needed. In terms of mem management you can make up your own interface for this, say IDisposable2, and get the same technical effect. This would however be a stupid thing to do because .net developers should know to call idisposable.dispose when object no longer needed. Also, there is built in language (c#) support for this interface (using {...}).

You write "I tried to implement IDisposable and then the ram goes down immideitly."

What matters is what your "implement" does. The code there should clean up unmanaged code, windows resources etc.

这篇关于内存释放与IDisposable和没有IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆