[c#] What is a callback?

What's a callback and how is it implemented in C#?

This question is related to c# callback

The answer is


callback work steps:

1) we have to implement ICallbackEventHandler Interface

2) Register the client script :

 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
    String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);

1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)

var finalfield= p1,p2,p3; UseCallBack(finalfield, ""); data from the client passed to server side by using UseCallBack

2) public void RaiseCallbackEvent(string eventArgument) In eventArgument we get the passed data //do some server side operation and passed to "callbackResult"

3) GetCallbackResult() // using this method data will be passed to client(ReceiveServerData() function) side

callbackResult

4) Get the data at client side: ReceiveServerData(text) , in text server response , we wil get.


Definition

A callback is executable code that is passed as an argument to other code.

Implementation

// Parent can Read
public class Parent
{
    public string Read(){ /*reads here*/ };
}

// Child need Info
public class Child
{
    private string information;
    // declare a Delegate
    delegate string GetInfo();
    // use an instance of the declared Delegate
    public GetInfo GetMeInformation;

    public void ObtainInfo()
    {
        // Child will use the Parent capabilities via the Delegate
        information = GetMeInformation();
    }
}

Usage

Parent Peter = new Parent();
Child Johny = new Child();

// Tell Johny from where to obtain info
Johny.GetMeInformation = Peter.Read;

Johny.ObtainInfo(); // here Johny 'asks' Peter to read

Links


A callback is a function that will be called when a process is done executing a specific task.

The usage of a callback is usually in asynchronous logic.

To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.

    public delegate void WorkCompletedCallBack(string result);

    public void DoWork(WorkCompletedCallBack callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
        DoWork(callback);
    }

    public void TestCallBack(string result)
    {
        Console.WriteLine(result);
    }

In today C#, this could be done using lambda like:

    public void DoWork(Action<string> callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        DoWork((result) => Console.WriteLine(result));
    }

A callback lets you pass executable code as an argument to other code. In C and C++ this is implemented as a function pointer. In .NET you would use a delegate to manage function pointers.

A few uses include error signaling and controlling whether a function acts or not.

Wikipedia


If you referring to ASP.Net callbacks:

In the default model for ASP.NET Web pages, the user interacts with a page and clicks a button or performs some other action that results in a postback. The page and its controls are re-created, the page code runs on the server, and a new version of the page is rendered to the browser. However, in some situations, it is useful to run server code from the client without performing a postback. If the client script in the page is maintaining some state information (for example, local variable values), posting the page and getting a new copy of it destroys that state. Additionally, page postbacks introduce processing overhead that can decrease performance and force the user to wait for the page to be processed and re-created.

To avoid losing client state and not incur the processing overhead of a server roundtrip, you can code an ASP.NET Web page so that it can perform client callbacks. In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.

Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx

If you are referring to callbacks in code:

Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.

More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx


I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?


A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.

Check out this link.


Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.

An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.

C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.


Delegates do the same thing as interface-based callbacks in C++ (COM uses these), although are much simpler to use.

Note that Microsoft put delegates into its Java implementation (J++) but Sun doesn't like them [java.sun.com] so don't expect to see them in the official version of Java any time soon. I've hacked together a preprocessor to let you use them in C++, so don't feel left out if you're not programming in C# or on the .NET platform (i.e. in Managed C++ or Visual Basic.NET).

If you're used to function pointers in C, a delegate is basically a pair of pointers rolled into one:

  • A pointer to an object (optional)
  • A pointer to a method of that object

That means a single delegate passes all the information needed to locate a function in your program, whether it's a static method or associated with an object.

You define them like this in C#:

public delegate void FooCallbackType( int a, int b, int c );

When you want to use them, you make delegate out of the function you want to call:

class CMyClass
{
    public void FunctionToCall( int a, int b, int c )
    {
        // This is the callback
    }

    public void Foo()
    {
        FooCallbackType myDelegate = new FooCallbackType(
            this.FunctionToCall );
        // Now you can pass that to the function
        // that needs to call you back.
    }
}

If you want to make a delegate to point to a static method, it just looks the same:

class CMyClassWithStaticCallback
{
    public static void StaticFunctionToCall( int a, int b, int c )
    {
        // This is the callback
    }

    public static void Foo()
    {
        FooCallbackType myDelegate = new FooCallbackType(
            CMyClass.StaticFunctionToCall );
    }
}

All in all, they do the same thing as interface-based callbacks in C++, but cause a bit less trouble because you don't need to worry about naming your functions or making helper objects, and you can make delegates out of any method. They're more flexible.


Dedication to LightStriker:
Sample Code:

class CallBackExample
{
    public delegate void MyNumber();
    public static void CallMeBack()
    {
        Console.WriteLine("He/She is calling you.  Pick your phone!:)");
        Console.Read();
    }
    public static void MetYourCrush(MyNumber number)
    {
        int j;
        Console.WriteLine("is she/he interested 0/1?:");
        var i = Console.ReadLine();
        if (int.TryParse(i, out j))
        {
            var interested = (j == 0) ? false : true;
            if (interested)//event
            {
                //call his/her number
                number();
            }
            else
            {
                Console.WriteLine("Nothing happened! :(");
                Console.Read();
            }
        }
    }
    static void Main(string[] args)
    {
        MyNumber number = Program.CallMeBack;
        Console.WriteLine("You have just met your crush and given your number");
        MetYourCrush(number);
        Console.Read();
        Console.Read();
    }       
}

Code Explanation:

I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.

Please let me know if you have any questions.