Bad practice? Non-canon usage of c#'s using st

2020-02-27 10:26发布

C# has the using statement, specifically for IDisposable objects. Presumably, any object specified in the using statement will hold some sort of resource that should be freed deterministically.

However, it seems to me that there are many designs in programming which have a single, definite beginning and end, but lack intrinsic language support. The using construct provides an opportunity to use the built in features of a code editor to, at least, clearly and naturally highlight the scope of such a design or operation.

What I have in mind is the sort of operation that frequently starts with a BeginXXX() and EndXXX() method, though there are plenty of different flavors, such as an asynchronous code execution that involves a "start" and a "join".

Take this naive example.

webDataOperation.Start();
GetContentFromHardDrive();
webDataOperation.Join();
// Perform operation that requires data from both sources

What if, instead, the Start method returned an object whose IDisposable.Dispose method performs the join operation.

using(webDataOperation.Start()) {
    GetContentFromHardDrive();
}
// Perform operation that requires data from both sources

Or, better yet, what I specifically had in mind: I have an object that does highly specialized graphics blitting and has a Begin() and End() method (a design also present in DirectX and XNA). Instead...

using(blitter.BlitOperation()) {
    // Do work
}
// Use result

It seems to be more natural and readable, but is it inadvisable, seeing as it uses the IDisposable interface and the using statement for unintended purposes? In other words, would this be on par with overloading an operator in a non-intuitive way?

6条回答
Melony?
2楼-- · 2020-02-27 11:12

This is a perfectly acceptable practice. These are called Factored Types, and the Framework Design Guidelines recommends doing just this.

Basically, if the type wraps an operation with a specific lifetime, using IDisposable and the using statement becomes an appropriate thing to consider.

I actually blogged about this specific topic here, as well.

查看更多
相关推荐>>
3楼-- · 2020-02-27 11:24

I recommend against it; my belief is that code is to effectively communicate with the maintainer of the code, not the compiler, and should be written with the maintainer's comprehension in mind. I try to use "using" only to dispose of a resource, typically an unmanaged resource.

I am in a minority. Most people it seems use "using" as a general purpose "I want some cleanup code to run even if an exception is thrown" mechanism.

I dislike this because (1) we already have a mechanism for that, called "try-finally", (2) it uses a feature for a purpose it was not intended for, and (3) if the call to the cleanup code is important, then why isn't it visible at the point where it is called? If it is important then I want to be able to see it.

查看更多
Bombasti
4楼-- · 2020-02-27 11:29

Just because you can (or because Phil Haack says it's okay), doesn't mean you should.

The basic rule of thumb: if I can read your code and understand what it's doing and what your intent was, then it's acceptable. If, on the other hand, you need to explain what you did, or why you did it, it's probably going to trip up junior developers maintaining the code.

There are many other patterns that can accomplish this with better encapsulation.

The bottom line: this "technique" buys you nothing and only acts to confuse other developers.

查看更多
孤傲高冷的网名
5楼-- · 2020-02-27 11:32

It's a common pattern, but personally, I believe that there's no excuse to abuse IDisposable like that when you can achieve the same effect in a much more obvious way with anonymous delegates and/or lambdas; i.e.:

blitter.BlitOperation(delegate
{
   // your code
});
查看更多
Animai°情兽
6楼-- · 2020-02-27 11:32

I'd say it's acceptable - in fact, I've used it in some projects where I wanted to have an action triggered at the end of a specific code block.

Wes Deyer used it in his LINQ to ASCII Art program, he called it action disposable (Wes works on the C# compiler team - I'd trust his judgment :D):

http://blogs.msdn.com/wesdyer/archive/2007/02/23/linq-to-ascii-art.aspx

class ActionDisposable: IDisposable
{
    Action action;

    public ActionDisposable(Action action)
    {
        this.action = action;
    }

    #region IDisposable Members

    public void Dispose()
    {
        this.action();
    }

    #endregion
}

Now you can return that from a function, and do something like this:

using(ExtendedConsoleWriter.Indent())
{
     ExtendedConsoleWriter.Write("This is more indented");
}

ExtendedConsoleWriter.Write("This is less indented");
查看更多
Juvenile、少年°
7楼-- · 2020-02-27 11:33

I think you should use IDisposable for what it's intended for, and nothing else. That is, if maintainability matters to you.

查看更多
登录 后发表回答