开发者

What is the purpose of this delegate usage?

Whilst poking around some code using a .NET Reflector for an app I don't have the source code for, I found this:

if (DeleteDisks)
{
  using (List<XenRef<VDI>>.Enumerator enumerator3 = list.GetEnumerator())
  {
    MethodInvoker invoker2 = null;
    XenRef<VDI> vdiRef;
    while (enumerator3.MoveNext())
    {
      vdiRef = enumerator3.Current;
      if (invoker2 == null)
      {
 开发者_高级运维       //
        // Why do this?
        //
        invoker2 = delegate {
          VDI.destroy(session, vdiRef.opaque_ref);
        };
      }
      bestEffort(ref caught, invoker2);
    }
  }
}
if (caught != null)
{
  throw caught;
}


private static void bestEffort(ref Exception caught, MethodInvoker func)
{
  try
  {
    func();
  }
  catch (Exception exception)
  {
    log.Error(exception, exception);
    if (caught == null)
    {
      caught = exception;
    }
  }
}

Why not call VDI.destroy() directly? Is this just a way of wrapping the same pattern of try { do something } catch { log error } if it's used a lot?


The reason appears to be to have a single function for handling and logging errors in operations that can fail: bestEffort. The delegate is used to wrap the action which can fail and pass it to the bestEffort function.


A delegate can be passed as an argument to a different function. The accepting function then does not have to know where that function is which class exposes it. It can invoke it and consume the results of it as it would from a regular method. The lambdas and then expression trees are built around delegates. Regular functions can't be evaluated at runtime which is possible with creating an expression tree with a delegate. You have you specific question answered already. So I will just add the general idea to the question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜