This trap comes from a requirement that the data needs to be processed asynchronously in the background. After processing, the event that is triggered to be processed is probably written as follows:
EmployeeCollection data = +=<EmployeeCollection> action = (d) =>, );
The code is quite simple, and the traps are also in it. Suppose DalHelper. fill (data) throws an exception. raiseEventLoaded () won't be executed and depends on data. the Loaded Event code will not be executed either. This is a bug. You should add a try... catch statement, or call the delegate EndInvoke method somewhere to handle possible exceptions during execution.
For such a simple requirement, add try... the EndInvoke of the catch or call delegate is too complicated. If the execution fails, the exception is thrown out, even if the current process is finished. Based on the principle of one write and multiple use, a dedicated help class is specially designed for dedicated asynchronous calls of such delegation. The help class code is as follows:
UnsafeBeginInvoke(Delegate del, = AsyncFire(Delegate del, InvokeDelegate(Delegate del, = ar.AsyncState
The core implementation is to encapsulate the call of the Delegate, call it in another delegate, and then use EndInvoke to release possible exceptions for another delegate, in this way, you can find the exceptions that occur when you call BeginInvoke and then delegate the execution.After this modification, the code just now can be called as follows:
EmployeeCollection data = +=<EmployeeCollection> action = (d) =>
The Code is as simple as the original design. If an exception occurs in the delegate, this error can also be found, rather than being hidden.
In addition, the implementation just now is not type-safe, and type-security can be solved through heavy load. The example is as follows:
UnsafeBeginInvoke (Delegate del, = AsyncFire (Delegate del, InvokeDelegate (Delegate del, = ar. asyncState add type-safe delegate BeginInvoke <T, U> (Action <T, U> BeginInvoke <T, U, V> (Action <T, U> Add type-safe delegateView Code
You can add the implementation of type security as needed.