Weak Events in C#

Hello Friend,

In the below post we will learn about how to use the generic WeakEventManager class to build a indirect connection to the publisher and subscriber of events. The normal “Events” directly connects the publisher and subscribers event object and which lead to memory leak since it may be chances are the subscribers objects are not garbage collected when GC try to collect because it is linked with publisher object.

To eliminate this problem .Net framework 4.5 introduced a new WeakEventManager Generic class which behaves as mediator and  creates a indirect connection between event publisher and subscribers objects. You need to add reference of “WindowsBase” assembly to make it working.

 

11

Let see this in a example code below

using System;
using System.Windows;

namespace EventExample
{
    public class Book
    {
        public string BookName { get; set; }
        public DateTime PublishDate { get; set; }
        public string ISBN { get; set; }
        public string Authors { get; set; }

    }

    // Custom event argument for passing extra information
    public class BookInfoEventArgs : EventArgs
    {
        public Book bookInfo { get; private set; }
        public BookInfoEventArgs(Book book)
        {
            this.bookInfo = book;
        }
    }

    public class BookPublisher
    {
        public event EventHandler BookSubscibers;

        public void PublishNewBook(Book book)
        {
            if (BookSubscibers != null)
            {
                BookSubscibers(this, new BookInfoEventArgs(book));
            }
        }
    }

    public class BookLover
    {
        public string Name { get; private set; }

        public BookLover(string name)
        {
            this.Name = name;
        }

        public void NewBookPublished(object sender, BookInfoEventArgs e)
        {
            Console.WriteLine("{0}, New Book Published, Here is the book information: \n" +
            "Book Name :{1}\nPublish Date: {2}\nISBN : {3}\nAuthor: {4}\n\n", this.Name, e.bookInfo.BookName, e.bookInfo.PublishDate, e.bookInfo.ISBN, e.bookInfo.Authors);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var publisher = new BookPublisher();

            var customer1 = new BookLover("Mahesh");

            WeakEventManager.AddHandler(publisher, "BookSubscibers", customer1.NewBookPublished);
            // publisher.BookSubscibers += customer1.NewBookPublished;

            var costomer2 = new BookLover("Madan");
            //publisher.BookSubscibers += costomer2.NewBookPublished;
            WeakEventManager.AddHandler(publisher, "BookSubscibers", costomer2.NewBookPublished);

            //Publish new Book
            publisher.PublishNewBook(new Book
            {
                BookName = "Learn C++",
                ISBN = "HJNJJJ782332HH",
                PublishDate = DateTime.Now,
                Authors = "Ramesh"
            });
            Console.ReadLine();
        }
    }
}

 

In the above code if you check the Main method then you will fine a line of code as below.

WeakEventManager.AddHandler(publisher, "BookSubscibers", customer1.NewBookPublished);

In the above code the first parameter is the event publisher object so ‘publisher’ object we have defined. The next parameter is the name of the event in the publisher object so in our example it is ‘BookSubscibers’ . The third and last parameter takes the subscriber object listener method so in our example it is ‘customer1.NewBookPublished’ method in the customer1 object.

Running this code you will see the below output which shows that the event publisher/subscriber model is properly working.

Capture

In the above post we have learned that how to use the generic WeakEventManager class for create link between publisher and subscriber object for events.

Hope this helps you. Thanks for reading 🙂

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s