What is the purpose of using this delegate?

While poking some code using .NET Reflector for the application, I don't have the source code, 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 to wrap the same try { do something } catch { log error } pattern if it is used a lot?

+4
source share
2 answers

The reason is that for processing and recording errors in operations that may fail, there is one function: bestEffort . The delegate is used to transfer an action that may fail and pass it to the bestEffort function.

+5
source

A delegate can be passed as an argument to another function. The receiving function then does not need to know where this function is, which class provides it. He can call it and consume the results, as it would be from the usual method. Delegates built lambda trees and then expression trees. Regular functions cannot be evaluated at runtime, which is possible when creating an expression tree using a delegate. You already have a specific question. Therefore, I will simply add a general idea to the question.

+1
source

Source: https://habr.com/ru/post/1333060/


All Articles