Search

Callback in C#

In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.
Lets see how we can implement the same in C# using Action(function object).

In the below example we have a class called CallbackExample with a DoSomething() method which counts from 0 to 9 with a delay of 1 second. Within an application we can't wait for 10 seconds for the process to completed that why we implement a callback called Callback which takes an object as parameter and this been invoked once the for loop completes counting from 0-9.
There is an important check to see if the callback is not null before invoking it, this handles a situation when callback is not been registered in the other end.
The main method registered the Callaback to display a message into the console before it calls the DoSomething method.

// Callback class example
public class CallbackExample
{
//define the callback
public Action<object> Callback;
public void DoSomething()
{
//this task it taking too long call me once done
for(int i=0;i<10;i++)
{
Console.WriteLine("Current counter is {0}",i);
Thread.Sleep(1000);
}
//important to check
if(Callback != null)
Callback("Task Completed");
}
}
//main
void Main()
{
CallbackExample _cbe = new CallbackExample();
_cbe.Callback = (o) => Console.WriteLine(o);
_cbe.DoSomething();
}
//eof
view raw Callback.cs hosted with ❤ by GitHub