views:

199

answers:

6
+4  Q: 

Callbacks in C#

I started coding in C# and have never had the opportunity to use callbacks though I have used delegates for event wiring. What is the real application of callbacks. I would be grateful if you could give some link that explains about callbacks in a straight forward way without C++ prerequisites.

+1  A: 

Any asynchronous action will rely on a callback.

Gerrie Schenck
A: 

A callback is a delegate is a function pointer. I dont think threads are a prerequisite for callbacks.

leppie
A: 

They are used to capture the results of an asychronous action.

AndyC
+8  A: 

A callback is actually a delegate, i.e. a reference to a function. Callbacks are often used in asynchronous (multi-threaded) scenarios to notify the caller when the asynchronous operation has finished: The asynchronous method gets a callback/delegate as a parameter and calls this delegate after it has finished its work, i.e. it "calls back". Using callbacks/delegates enables the caller to decide which operation is called because he passes in the parameters.

Example:
When the user starts a long running operation by clicking on a button, you could set the mouse pointer to a WaitCursor and start the long running operation on another thread. Now, how do you know when you may reset the mouse pointer to the normal ArrowCursor? Answer: using Callbacks. You simply create a method which resets the cursor to an arrow and then pass a reference to this method (a delegate) as the callback parameter. Then this method is called when the operation finished, and your cursor is reset.

Actually, events are also some sort of callbacks: you register a delegate to be notified when a certain event occurs. When this event occurs, you are called back using the provided delegate.

gehho
+1  A: 

If you are familiar with WPF, a nice example are Dependency Properties. You register then using DependencyProperty.Register:

public static DependencyProperty Register(
    string name,
    Type propertyType,
    Type ownerType,
    PropertyMetadata typeMetadata,
    ValidateValueCallback validateValueCallback
)

As the last parameter, you pass a function of yours that is called by the framework when some work needs to be done (validating the value).

Heinzi
A: 

Delegate holds a reference to a method which make it ideal candidate for callback.

I have tried to explain it with a simple example: Meditor class acts like a chat server where controllers can sign on. Inorder to communicate, Controllers need to implement a method which will act as callback method.

public class Mediator
    {
        //instruct the robot to move.
        public delegate void Callback(string sender, string receiver, Message msg);


        Callback sendMessage;

        //Assign the callback method to the delegate          
        public void SignOn(Callback moveMethod)
        {
            sendMessage += moveMethod; 
        }

        public void SendMessage(string sender, string receiver, string msg)
        {
            sendMessage(sender, receiver, msg);
        }
    }


public class Controller : Asset
    {
        string readonly _name; 
        Mediator _mediator; 
        public Controller(Mediator m, string name)
        {
              _name = name;
             _mediator = m;
            //assign the call back method
            _mediator.SignOn(Notification);
        }

        public void Notification(string sender, string receiver, string msg)
        {
            if (receiver == _name )
            {
               Console.WriteLine("{0}: Message for {1} - {2}".FormateText(sender, 
                 receiver, msg)); //I have create extension method for FormatText.
            }
        }

        public void Mobilize(string receiver, string msg)
        {
              _mediator.SendMessage(_name, receiver, msg);
        }

    }

static void Main(string[] args)
{

    Mediator mediator;
    mediator = new Mediator();

    //accept name here...

    Controller controller1 = new Controller(mediator, "name1");
    Controller controller2 = new Controller(mediator, "name2");
    controller1.Mobilize("name2","Hello");
    controller1.Mobilize("name1", "How are you?");
}

output will be:

name1: Message for name2 - Hello
name2: Message for name1 - How are you?
ARS