C # Callbacks

I started coding in C # and never had the opportunity to use callbacks, although I used delegates to post events. What is the real use of callbacks. I would appreciate it if you could give a link that explains callbacks in a direct way without C ++ prerequisites.

+5
source share
6 answers

The callback is actually a delegate, i.e. a function reference. Callbacks are often used in asynchronous (multi-threaded) scripts to notify the caller when the asynchronous operation is completed: the asynchronous method receives a callback / delegate as a parameter and calls that delegate after it completes, i.e. It “rolls back.” "Using callbacks / delegates allows the caller to decide which operation is being called because he is passing parameters.

:
, , WaitCursor . , , reset ArrowCursor? : . , , () . , , reset.

, : . , .

+9

.

+1

- - . , .

+1

WPF, . , DependencyProperty.Register:

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

, , ( ).

+1

.

0

, .

: Meditor -, . , .

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?
0
source

All Articles