Use of Finalize/Dispose method in C#

后端 未结 13 2048
轮回少年
轮回少年 2020-11-21 23:20

C# 2008

I have been working on this for a while now, and I am still confused about the use of finalize and dispose methods in code. My questions are below:

13条回答
  •  甜味超标
    2020-11-21 23:41

    Using lambdas instead of IDisposable.

    I have never been thrilled with the whole using/IDisposable idea. The problem is that it requires the caller to:

    • know that they must use IDisposable
    • remember to use 'using'.

    My new preferred method is to use a factory method and a lambda instead

    Imagine I want to do something with a SqlConnection (something that should be wrapped in a using). Classically you would do

    using (Var conn = Factory.MakeConnection())
    {
         conn.Query(....);
    }
    

    New way

    Factory.DoWithConnection((conn)=>
    {
        conn.Query(...);
    }
    

    In the first case the caller could simply not use the using syntax. IN the second case the user has no choice. There is no method that creates a SqlConnection object, the caller must invoke DoWithConnection.

    DoWithConnection looks like this

    void DoWithConnection(Action action)
    {
       using (var conn = MakeConnection())
       {
           action(conn);
       }
    }
    

    MakeConnection is now private

提交回复
热议问题