Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Events : Subscribing Events

The publisher/subscriber relationship is a one-to-many relationship. For each publisher there can be zero or more subscribers. Conversely, a subscriber can subscribe to multiple events. For example, a form can subscribe to a button click and a text change event. Subscribers add a delegate to an event to register for the event. The delegate is a wrapper for the function to be called when the event is raised. Subscribe to an event using the add method or the += assignment operator:

using System;

namespace Example.Events
{
    class Publisher
    {
        public event EventHandler MyEvent;
    }

    public class Subscriber
    {
        public static void Handler(object obj, EventArgs args)
        {
        }

        public static void Main()
        {
            Publisher pub = new Publisher();
            pub.MyEvent += Handler;

            // other processing
        }
    }
}

Cancel a subscription to a delegate with the -= assignment operator.

September 30, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

C# .NET Events : Publishing Events

Both classes and objects can publish events. Static events are published at classes, whereas objects publish instance events. Multicast delegates underlie events. You must create a delegate for the event or leverage a predefined event. Events are defined with the event keyword. This is the syntax for defining an event:

  • accessibility event delegatename eventname

Events are defined as a field in a class. The accessibility of an event is typically public or protected. Protected events restrict subscribers to child objects. A public event is available to every interested subscriber. Delegate name is the underlying delegate of the event, which defines the signature of the event. Event name is the identity of the event.

public delegate void DelegateClass();
public event DelegateClass MyEvent;

As a best practice, event handlers should return void and have two arguments. EventHandler is a predefined delegate created for this purpose. It is included in the .NET Framework class library (FCL) and prevents you from having to declare a separate delegate for the standard event type. The first parameter is the object that raised the event. The second parameter is an EventArgs derived instance, which offers optional data that further explains the event.

Internally, events declared in a class become a field of that class. Delegates used to define the event, which is a multicast delegate, are types used for the field. The C# compiler also inserts methods to add and remove subscribers to the event. The names of the methods are add_EventName and remove_EventName, respectively. The fourth member added to the class is the event itself.

September 29, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

C# .NET Events : What is an Event: Definition and Purpose

An event is an occurrence that an object or class wants to notify someone else about. (The someone else is either another object or class.) A button notifies a form object that someone clicked on the button. A timer notifies some other object that a time period has elapsed. An application domain notifies an application of an unhandled event. A Web application notifies an object of an application event. You can create custom events, such as a device notifying a monitoring application that data transmission has started or stopped. This list of events is somewhat eclectic, which underscores that there is no strict definition. Events are literally anything worth notifying someone else about. Public events are exposed as public members of a publisher class, such as a button class. You can also have private and protected events that are used within the realm of the containing or derived class.

Any object or class interested in an event can subscribe. Subscribers register for an event by submitting a delegate. The delegate must be single cast and contain a single function pointer. That function is the subscriber’s response to the event. When the event is raised, the publisher calls the function, affording the subscriber an opportunity to respond to the event. For this reason, the function is called an event handler. Events can have multiple subscribers. A device could publish a power-off event in which multiple applications might want to be notified and respond.

September 23, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

Generic Anonymous Methods in C# .NET

Anonymous methods can use generic parameters of the class or delegate. However, anonymous methods cannot define new generic parameters and constraints. Here are two examples of anonymous methods using generic parameters:

public delegate void ADelegate<T>(T tvalue);

public class ZClass
{
    public void MethodA()
    {
        ADelegate<int> del = delegate(int var)
        {
        };
    }
}
public class YClass<T>
{
    public delegate void BDelegate(T tValue);
    public void MethodA()
    {
        BDelegate del = delegate(T tValue)
        {
        };
    }
}

September 21, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

C# .NET Anonymous Methods : Limitations

Although anonymous methods are similar to other methods, they have some limitations. In my previous posts, I have already mentioned some. Here are another two of them.

  • They cannot be a member method.
  • They cannot be an unsafe method.

While working with anonymous methods, keep the following things in your mind,

  • Do not attempt to jump out of an anonymous method.
  • Do not use a ref or out outer variable in an anonymous method.
  • Do not define new generic parameters or constraints.
  • Do not apply attributes to anonymous methods.
  • Do not use anonymous method with -= assignment operator.

September 18, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

Site for Bookmarks

One of my friends, knocked me on the IM today. He is an owner of a software house. They have developed a bookmark site. He told me to use it for a while and to say if there is any bug available. I found that it is a cool and simple bookmark site with some exiting features. But you must need Mozilla Firefox to use it. It incorporates a tool in the browser. I hope it will help you in many ways. And its FREE.

So far I have found out, pages, texts, images and videos can be bookmarked. You should take a look. And remember to send feedbacks.

September 18, 2008 Posted by shiman | Miscellaneous | , | No Comments Yet

Anonymous Method in C# .NET : Outer Variables

Anonymous methods can refer to local variables of the containing function and class members within the scope of the method definition. Local variables used in an anonymous method are called outer variables.

The scope of a local variable is closely linked to the method in which the local is declared. When the method ends, local variables are removed from memory. Local variables used in an anonymous method are captured, which extends the lifetime of the variable. The lifetime of a captured or outer variable is of the same as that of the delegate. The outer variable is removed when the delegate is garbage-collected. In the following code, the local variable of MethodA is captured in the anonymous method. The lifetime of the local variable would usually end when MethodA is exited. However, the delegate is garbage-collected until the end of the program, which extends the lifetime of the local variable for the entire program.

using System;

namespace Examples.AnonymousMethod
{
    public delegate void DelegateClass(out int arg);

    public class Program
    {
        public static void Main()
        {
            DelegateClass del = MethodA();
            int var;
            del(out var);

            Console.WriteLine(var);

            Console.ReadKey();
        }

        public static DelegateClass MethodA()
        {
            int local = 0;
            return delegate(out int arg)
            {
                arg = ++local;
            };
        }
    }
}

Because the lifetime of outer variables is aligned with the delegate, it remains persistent across invocations of the anonymous method. In the following code, the anonymous method is invoked thrice through the delegate. As a local variable, local would be initialized on each call to the method. However, as an outer variable, it is initialized once in MethodA and maintains its value across multiple calls to the anonymous method. Therefore, the value displayed is 3.

using System;

namespace Examples.AnonymousMethod
{
    public delegate void DelegateClass(out int var);

    public class Program
    {
        public static void Main()
        {
            DelegateClass del = MethodA();
            int var;
            del(out var);
            del(out var);
            del(out var);
            Console.WriteLine(var);

            Console.ReadKey();
        }

        public static DelegateClass MethodA()
        {
            int increment = 0;
            return delegate(out int var)
            {
                var = ++increment;
            };
        }
    }
}

The C# compiler creates a private nested class for anonymous methods that capture local variables, whereas anonymous methods that contain no outer variables are implemented as private static methods. The nested class has a public field for each outer variable used in the anonymous method. The local variable is persisted to this public field. It also contains a named method for the anonymous method. The named method has the same signature as the related delegate. This is the method used to initialize the wrapper delegate.

Locals are fixed variables and are not normally available to garbage collection. Local variables are removed from memory when the applicable method is exited. When a local variable is captured, it becomes a movable variable. Movable variables are placed on the managed heap. As such, outer variables then become available for garbage collection. For this reason, captured variables must be pinned or otherwise fixed before being used with unsafe code.

September 16, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

Anonymous Method in C# .NET

An anonymous method is a nameless method. Sometimes a function is intended exclusively for a delegate. Without an anonymous method, you would have to define a separate function as part of a class. The function can then be assigned to the delegate. Assigning an anonymous method prevents creating a separate method. This is cleaner and more convenient than a named method. Anonymous methods can substitute for delegates as parameters, return values, and in other situations.

Define an anonymous method with the delegate keyword. This code assigns an anonymous method to a delegate:

using System;
using System.Threading;

namespace Examples.AnonymousMethod
{
    public delegate void DelegateClass();

    public class Program
    {
        public static void Main()
        {
            DelegateClass del = delegate
            {
                Console.WriteLine("Running anonymous method");
            };
            del();

            Console.ReadKey();
        }
    }
}

In the preceding example, the anonymous method does not have a signature. The signature of the anonymous method is inferred from the delegate signature, which is another example of delegate inference. Despite not having a signature, the return of the anonymous method must match the delegate return. The advantage of an anonymous method without a signature is its compliance with almost any delegate. The disadvantage is that anonymous methods defined without a signature cannot access the parameters of the delegates. This means that the anonymous method cannot utilize the parameters. For this reason, anonymous methods without a signature cannot be employed where delegates have out parameters. Out parameters must be initialized in the called method, which is impossible in an anonymous method. When an anonymous method is called through the delegates, the parameters must still be provided, even if ignored inside the method. Of course, if the delegate has no parameters, none should be provided.

This is the syntax of an anonymous method:

  • delegate optional_signature {anonymous method expression}

The C# compiler performs several tasks to assign an anonymous method without a signature to a delegate:

  1. Validates the signature of the delegate—no out parameters
  2. Infers the signature of the anonymous method from the delegate
  3. Confirms that the return type of the delegate is compatible with the anonymous method
  4. Creates a new delegate that is initialized with a function pointer to the anonymous method

Anonymous methods can be assigned a signature, which is appended to the delegate keyword. This restricts the anonymous method to a delegate with a matching signature and return type. Like conventional methods, the parameters are initialized with the parameters from the delegate call. This is an example of an anonymous method with a signature:

using System;
using System.Threading;

namespace Examples.AnonymousMethod
{
    public delegate int DelegateClass(out int param);

    public class Program
    {
        public static void Main()
        {
            int var;
            DelegateClass del = delegate(out int inner)
            {
                inner = 12;
                Console.WriteLine("Running anonymous method");
                return inner;
            };
            del(out var);
            Console.WriteLine("Var is {0}", var);

            Console.ReadKey();
        }
    }
}

As demonstrated in the preceding code, anonymous methods can be used for delegates. The exception is the -= assignment operator. Because the anonymous method is unnamed, it cannot be used to remove a named method from a multicast delegate. This is the exception to freely substituting delegates with anonymous methods.

Actually, anonymous methods are not nameless. The C# compiler implements the anonymous method as the named method in the containing class. The generated method is both static and private. The wrapper delegate is initialized with this method. The following format is used to name anonymous methods:

  • <functionname>uniqueid

The function name is the function in which the anonymous method is implemented. The unique identifier is a combination of a letter and number. The method has the same signature as the target delegate.

The wrapper delegate initialized with the anonymous method is also added to the class as a static and private field. This is the format of the wrapper delegate. The identifier is a compiler-generated number, whereas # is a character added to the name of the wrapper delegate.

  • <>id__CachedAnonymousMethodDelegate#

The following code offers two delegates and anonymous methods: 

using System;

namespace Examples.AnonymousMethod
{

    public delegate void ADelegate(int param);
    public delegate int BDelegate(int param1, int param2);

    public class Program
    {
        public static void Main()
        {
            ADelegate del = delegate(int param)
            {
                Console.WriteLine("param = {0}", param); ;
            };

            del(5);

            Console.ReadKey();

        }

        public int MethodA()
        {
            BDelegate del = delegate(int param1, int param2)
            {
                Console.WriteLine("param1 = {0}, param2 = {1}", param1, param2);
                return 0;
            };
            return 0;
        }
    }
}

September 14, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | 5 Comments

Caution : Exceptions in C# .NET Multicast Delegates

What happens if an unhandled exception is raised in a multicast delegate? If the delegate is invoked inside a protected block of code, the exception is trapped. The invocation list is called until an exception occurs. Functions later in the invocation list do not execute. Let us assume that the invocation list has pointers to MethodA, MethodB, MethodC, and MethodD. They were also added to the delegate in that order. If an unhandled exception is raised in MethodB, MethodC and MethodD are not called. The situation might appear to be more complicated if the exception is raised in a delegate that is running asynchronously. In this circumstance, the exception is raised on a different thread. However, the run time will route the exception back to the calling thread, as evidenced in the following code. Therefore, the exception is handled as if the delegate were called synchronously.

using System;
using System.Threading;

namespace Examples.Delegates
{

    public delegate void DelegateClass();

    public class Program
    {
        /// <summary>
        /// This code contains unhandled exception
        /// </summary>
        public static void Main()
        {
            Console.WriteLine("Running on primary thread");
            try
            {
                DelegateClass del = MethodA;
                IAsyncResult ar = del.BeginInvoke(null, null);
                del.EndInvoke(ar);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Running on primary thread");
                Console.WriteLine("Exception caught: " + ex.Message);
            }
        }

        public static void MethodA()
        {
            if (Thread.CurrentThread.IsThreadPoolThread == true)
            {
                Console.WriteLine("Running on a thread pool thread");
            }
            else
            {
                Console.WriteLine("Running on primary thread");
            }

            throw new Exception("failure");
        }
    }
}

September 11, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet

C# .NET Delegates : Asynchronous Invocation (EndInvoke Method)

EndInvoke provides that the result of an asynchronous operation is callable in the completion routine or the thread of the delegate caller. EndInvoke has the same signature as the delegate without the value parameters and has an additional final parameter, which is an IAsyncResult object. To obtain the signature of the EndInvoke method, remove the value parameters from the delegate signature and add an IAsyncResult parameter. The IAsyncResult parameter is the same IAsyncResult object that is returned from BeginInvoke. The return type of EndInvoke is identical to the return of the delegate.

This is the syntax of the EndInvoke method:

  • returntype EndInvoke(ref_out_arguments, IAsyncResult ar)

Calling EndInvoke before functions of the asynchronous delegate has finished executing blocks the caller until the operation is completed. For each BeginInvoke, there should be a complementing EndInvoke to confirm the results of the operation, detect an exception, and to allow the CLR to properly clean up the delegate. Calling the EndInvoke method more than once on the same delegate yields undefined results and should be avoided.

Here is sample code for the EndInvoke method:

using System;
using System.Threading;

namespace Examples.Delegates
{
    public delegate int DelegateClass(out DateTime start, out DateTime stop);

    public class Program
    {
        public static void Main()
        {
            DelegateClass del = MethodA;
            DateTime start;
            DateTime stop;
            IAsyncResult ar = del.BeginInvoke(out start, out stop, null, null);

            ar.AsyncWaitHandle.WaitOne();

            // code segments...

            int elapse = del.EndInvoke(out start, out stop, ar);
            Console.WriteLine("Start time: {0}", start.ToLongTimeString());
            Console.WriteLine("Stop time: {0}", stop.ToLongTimeString());
            Console.WriteLine("Elapse time: {0} seconds", elapse);

            Console.ReadKey();
        }

        public static int MethodA(out DateTime start, out DateTime stop)
        {
            start = DateTime.Now;
            Thread.Sleep(5000);

            stop = DateTime.Now;
            return (stop - start).Seconds;
        }
    }
}

September 11, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet