DEV Community

Hootan Hemmati
Hootan Hemmati

Posted on

How to use the IDisposable interface in event handlers in C#

The IDisposable interface provides a way to release unmanaged resources such as file handles, network connections, and database connections when they are no longer needed. The following code demonstrates how to implement the IDisposable interface in an event handler to ensure that objects are properly disposed of when they are no longer needed.

using System;
using System.IO;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var handler = new EventHandler())
            {
                handler.SomeEvent += (sender, e) =>
                {
                    Console.WriteLine("Event fired!");
                };

                Console.ReadLine();
            }
        }
    }

    class EventHandler : IDisposable
    {
        private FileStream _fileStream;

        public event EventHandler<EventArgs> SomeEvent;

        public EventHandler()
        {
            _fileStream = new FileStream("test.txt", FileMode.Create);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_fileStream != null)
                {
                    _fileStream.Dispose();
                    _fileStream = null;
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~EventHandler()
        {
            Dispose(false);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, we create a custom EventHandler class that implements the IDisposable interface. The EventHandler class has a FileStream field named _fileStream that is used to create a file. The class also has an event named SomeEvent that can be raised by the client code.

In the Main method, we create an instance of the EventHandler class using the using statement to ensure that the instance is properly disposed of when it is no longer needed. We then attach an event handler to the SomeEvent event. Finally, we wait for user input before exiting the program.

The EventHandler class overrides the Dispose method to release any unmanaged resources that it is holding onto. The Dispose method is also responsible for suppressing the finalization of the object if it is called by the client code.

In the event handler for the SomeEvent event, we simply print out a message to the console to indicate that the event has been fired.

By using the IDisposable interface in our EventHandler class, we can ensure that any unmanaged resources are properly disposed of when the instance is no longer needed. This helps prevent memory leaks and other resource-related issues that can cause problems in your application.

Top comments (0)