简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM