Delegates CallBack in C#


In this article we are going to discuss how to implement delegate callback with example in C#.

Delegate Callback Introduction

In C#, a delegate callback is a way to pass a method as a parameter to another method, allowing that method to call (or callback) the method you passed. Callbacks are useful when you need to execute certain code after a specific task is completed.

For example, you can use a callback to notify when a file has finished downloading or when a computation has completed.

Using callbacks with delegates in C# provides several advantages, making your code more flexible, modular, and easier to maintain.

Benefits Using a Delegate Callback

  1. Decoupling Code - Delegates allow you to separate the logic of a method from the logic of a callback. This helps in making your code more modular and easier to manage. By passing the method to be executed as a parameter, you decouple the caller and the callee.
  2. Asynchronous Programming - Callbacks are often used in asynchronous programming to handle tasks that take an uncertain amount of time to complete (like I/O operations, network requests, etc.). You can pass a callback delegate to be invoked once the asynchronous task is completed.
  3. Event Handling - Delegates and callbacks are foundational to the event-driven programming model in C#. Events in C# are essentially a list of delegate instances. Callbacks provide a way to respond to events or changes in the state of an object.
  4. Customizable Logic - By using delegates as callbacks, you allow the caller to customize the behavior of your methods without modifying the method itself. This makes your methods more reusable and flexible.
  5. Callback Mechanism - Callbacks are useful when you need to execute certain code after a specific task is completed. For example, you can use a callback to notify when a file has finished downloading or when a computation has completed.

Here, I will explain Callback by Delegate.

How It Works

  1. Define the Delegate - SimpleCallback delegate can point to any method that returns void and takes a string parameter.
  2. Create a Method to be Called Back - ShowMessage method will be called when the work is done.
  3. Pass the Method as a Delegate - In the Main method, we create an instance of the Worker class and pass the ShowMessage method to the DoWork method using the delegate.
  4. Perform Work and Callback - The DoWork method simulates some work, and once the work is done, it calls the ShowMessage method through the delegate, printing "Work completed!" to the console.
using System;

public delegate void SimpleCallback(string message);
public class Worker
{
    public void DoWork(SimpleCallback callback)
    {
        // Simulate some work
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Working...");
            System.Threading.Thread.Sleep(1000); //work sleeping for 1 second
        }
        // Work is done, call the callback method
        callback("Work completed!");
    }
}
class Program
{
    public static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }
    static void Main()
    {
        Worker worker = new Worker();
        SimpleCallback callback = new SimpleCallback(ShowMessage);
        //Start the work and pass the callback method
        worker.DoWork(callback);
    }
}

Output

Delegate CallBack in C#
Prev Next