如何检查是否对象已被释放在C# [英] How to check if object has been disposed in C#

查看:2359
本文介绍了如何检查是否对象已被释放在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
怎样才能判断一个IDisposable的对象引用配置?

有检查对象已被释放不同的方法,然后

Is there a method to check if object has been disposed different then

try
{
    myObj.CallRandomMethod();
} catch (ObjectDisposedException e)
{
    // now I know object has been disposed
}

在我来说,我使用的TcpClient 类,它具有关闭()方法,处置对象,这可以在一段代码我没有控制发生。在这种情况下,我想有更好的解决方案,然后捕获异常。

In my case I'm using TcpClient class that has Close() method which disposes object and this can happen in piece of code I don't have control of. In this case I would like to have better solution then catching exception.

推荐答案

一个好方法是从TcpClient的派生并重写处置(布尔)方法:

A good way is to derive from TcpClient and override the Disposing(bool) method:

class MyClient : TcpClient {
    public bool IsDead { get; set; }
    protected override void Dispose(bool disposing) {
        IsDead = true;
        base.Dispose(disposing);
    }
}

如果其它代码创建了哪个都不行实例。然后,你就必须做一些绝望喜欢使用反射来获取私人m_CleanedUp成员的值。或捕获异常。

Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.

坦率地说,没有一个是这很可能走到一个很好的结束。你真的没有的要写入的TCP端口。但你不会,那bug的代码,你无法控制,现在是在的<​​em>您的代码控制。你已经增加了错误的影响。谈起这些代码的拥有者和工作出来的东西是迄今为止最好的解决方案。

Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.

这篇关于如何检查是否对象已被释放在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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