我如何确保对象在.NET妥善处理? [英] How do I ensure that objects are disposed of properly in .NET?

查看:123
本文介绍了我如何确保对象在.NET妥善处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 Windows窗体应用程序在.NET 2采用连续运行C#。对于大多数人认为我很高兴,但据报道,我认为它已经失败偶尔为之。我能够监控其性能的50%的时间,我从来没有看到失败的。

I have created a Windows Forms application in .NET 2 using C# that runs continuously. For most accounts I am pleased with it, but it has been reported to me that it has failed occasionally. I am able to monitor its performance for 50% of the time and I have never noticed a failure.

在这一点上我很担心,也许程序正在使用太多的资源,而不是配置资源时,他们不再需要。

At this point I am concerned that perhaps the program is using too many resources and is not disposing of resources when they are no longer required.

什么是正确处理已创建的定时器和类似的图形路径,SQL连接等图形对象或者我可以依靠的Dispose方法来照顾所有垃圾收集创建的对象的最佳实践?

What are the best practices for properly disposing created objects that have created timers and graphical objects like graphics paths, SQL connections, etc. or can I rely on the dispose method to take care of all garbage collection?

另外: 有没有办法,我可以监视应用程序使用资源的方式?

Also: Is there a way that I could monitor resources used by the application?

推荐答案

最好的做法是确保所有对象实施的 IDisposable的接口称为废弃一旦对象不再需要的。

Best practice is to make sure that all objects implementing the IDisposable interface is called Dispose on as soon as the object is no longer required.

这可以完成,也可与使用关键字或<一HREF =htt​​p://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx相对=nofollow>尝试/终于的结构。

This can be accomplished either with the using keyword or try/finally constructs.

在一个WinForms形式,具有分配给窗体的寿命资源,有所不同的方法是必要的。因为形式本身实现IDisposable这是一个迹象,在时间处置某些时候会被调用这种形式。你要确保你的可支配的资源得到处理在同一时间。要做到这一点,你应该覆盖的形式的Dispose(BOOL处置)的方法。实施应​​该是这个样子:

Within a WinForms form that has resources allocated for the lifetime of the form, a somewhat different approach is necessary. Since the form itself implements IDisposable this is an indication that at some point in time Dispose will be called on this form. You want to make sure that your disposable resources gets disposed at the same time. To do this you should override the forms Dispose(bool disposing) method. The implementation should look something like this:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        // dispose managed resources here
    }
    // dispose unmanaged resources here
}

在表单组件的注解:如果你的对象实现了 IComponent的界面,你可以将实例的形式的集装箱。容器将处理组件的照顾,当容器本身配置。

A note on Components in forms: if your object implements the IComponent interface you can place the instance in the forms Container. The container will take care of disposing components when the container itself is disposed.

这篇关于我如何确保对象在.NET妥善处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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