代码之家  ›  专栏  ›  技术社区  ›  Ilya Ryzhenkov

IUsable:以比IDisposable更好的方式控制资源

  •  1
  • Ilya Ryzhenkov  · 技术社区  · 16 年前

    当using construct的代码块作为委托传递给函数时,我希望C#中有“可用”模式:

    class Usable : IUsable
    {
      public void Use(Action action)  // implements IUsable
      {
        // acquire resources
         action();
        // release resources
      }
    }
    

    在用户代码中:

    using (new Usable())
    {
      // this code block is converted to delegate and passed to Use method above
    }
    

    赞成的意见:

    • 受控执行,例外情况
    • 在调用堆栈中可以看到使用“可用”的事实

    欺骗:

    • 委托成本

    你认为它是可行和有用的,如果它没有任何问题,从语言的角度看?你能看到什么陷阱吗?

    proposed 以下

    using(new Usable(delegate() {
        // actions here
    }) {}
    

    它可以在这样的示例场景中工作,但通常您已经分配了资源,并希望它看起来像这样:

    using (Repository.GlobalResource) 
    { 
      // actions here 
    }
    

    你可以重写,只要

    Repository.GlobalResource.Use(() =>
    {
      // actions here
    });
    

    3 回复  |  直到 7 年前
        1
  •  3
  •   nullDev    16 年前

    我觉得这种模式没什么用,因为:

    我已经使用IDisposable成功地将这种模式用于数据库操作。

        2
  •  2
  •   Hallgrim    16 年前

    关于:

    class Usable<T> where T : ICriticalResource, new()
    {
        static void Do(Action<T> action) {
            ICriticalResource resource = new T();
            resource.Acquire();
            action(resource);
            resource.Relese();
        }
    }
    

    然后将它用于实现ICritialResource的所有操作。

    Usable<SomeResource>.Do(resource => resource.SomeMethod());
    

    另一种选择是按原样使用IDisposable。是的,它可能没有它可能是优雅的,但至少大多数人已经习惯了。

        3
  •  1
  •   David Schmitt    16 年前

    using(new Usable(delegate() {
        // actions here
    }) {}
    

    当然,在某些函数中封装它,或者直接实现try/finally可能不仅有用,甚至有点漂亮。