关于dispose:在C#中实现IDisposable

Implementing IDisposable in C#

本问题已经有最佳答案,请猛点这里访问。

我正试图在示例程序中实现IDisposable。如果我在using块语句中使用sqlconnection类,它将自动释放它。

1
2
3
4
5
6
7
8
9
10
11
12
13
public int testCon()
{
    using (SqlConnection conn = new SqlConnection("Conn string"))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText ="SELECT COUNT(1) FROM Carsd";

            return (int)cmd.ExecuteScalar();
        }
    }
}

我已经创建了一个类并实现了IDisposable。我在using块语句中创建了一个新实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Program
{
    static void Main(string[] args)
    {
        testDispose objTestDispose;

        using (objTestDispose = new testDispose())
        {
            objTestDispose.UserName ="testUser";
            objTestDispose.PassWord ="testPassword";                                
        }

        Console.WriteLine("Check obj of testDispose Class" + objTestDispose.UserName);
        Console.WriteLine("Check obj of testDispose Class" + objTestDispose.PassWord);
        Console.ReadLine();

    }        
}

public class testDispose : IDisposable
{
    public string UserName { get; set; }
    public string PassWord { get; set; }

    public void Dispose()
    { }              
}

我相信,使用块会自动调用Dispose方法。所以,如果我在using块中创建一个新实例,它将在现有using块之后被释放。但是,我仍然能够访问使用块之外的objTestDispose对象。为什么?

请建议。

乌达特

BWA先生……谢谢你把我的问题复制了。但你应该知道我是一个学生和学习者。我心里有这个问题,所以我在这里问过。**不能说IDisposable接口仅用于非托管资源。**我还可以删除托管资源。这取决于情况。根据以下链接-

What if your object has allocated a 250MB System.Drawing.Bitmap (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there – waiting for the garbage collector to eventually come along and free it? What if there's an open database connection? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.

If the user has called Dispose() (meaning they no longer plan to use
the object) why not get rid of those wasteful bitmaps and database
connections?

So now we will:

get rid of unmanaged resources (because we have to), and get rid of
managed resources (because we want to be helpful)


您仍然可以访问它,因为您在using块的范围之外定义了它,并且还没有将其设置为空。

注意,using没有将对象设置为空,它只是意味着将调用Dispose()方法,这为您提供了一种合同保证的方法来处理任何非托管资源,否则这些资源不会被垃圾收集器清除。

你还应该考虑你的陈述的逻辑:

I believe, using block automatically call dispose method. So, if I am create a new instance in using block, it would be dispose after existing using block.

…对象如何将其自身设置为空?


正在调用Dispose,但它不做任何销毁对象本身的操作(您会注意到框架内的许多IDiposable类另外还有一个IsDisposed属性来指示是否释放了非托管资源)。


来自MSDN

IDisposable接口

Provides a mechanism for releasing unmanaged resources.

The primary use of this interface is to release unmanaged resources.
The garbage collector automatically releases the memory allocated to a
managed object when that object is no longer used. However, it is not
possible to predict when garbage collection will occur. Furthermore,
the garbage collector has no knowledge of unmanaged resources such as
window handles, or open files and streams. Use the Dispose method of
this interface to explicitly release unmanaged resources in
conjunction with the garbage collector. The consumer of an object can
call this method when the object is no longer needed.

这用于释放命名资源,而不是用于销毁对象本身。