Showing posts with label Delegates. Show all posts
Showing posts with label Delegates. Show all posts

Friday, 19 January 2018

Logging With Log4Net | Console App | Parallel Vs Delegate


In this article, we will see how to enable logging using log4net and see the advantage of using Parallel Invoke over delegate.
Here is the simple console and I added the reference of Log4net; using log4net api I added tracing statements as shown.
I have used delegate to invoke LogM1 and LogM2 methods that would in turn invoke M1 and M2 methods using Parallel For Loop, M1 and M2 writes the trace details as shown below.
Lets run and verify the logs. Though, we use delegate to invoke the methods, we clearly see, M2 is invoked or started; post completion of M1 method. As Parallel FOR loop invokes M1 and M2, logging are captured in a random manner.
Instead of delegate, lets now refactor the code to use Parallel Invoke method as shown below.
Lets run and verify the behaviour. Both M1 and M2 are parallel invoked and all the logs are captured in a random manner; execution time is also faster comparatively to earlier way using delegate.

Thursday, 4 August 2016

Delegates and Events in C Sharp

In this article, I will brief about delegates and events. C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

Declaring, Instantiating and Multicasting of delegates
Below screen shot explains, void vs return type delegates
Events and delegates work hand-in-hand to provide a program’s functionality. Below code shows logging feature using event delegate.