Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 581
softwarematter Avatar asked Apr 13 '10 10:04

softwarematter


People also ask

Does C have callback?

Callback functions are one the most powerful mechanisms in C. A callback function is any code that is passed as an argument to some other code, in such a way that this last code is able to call back, i.e., to execute, the code passed as argument. In C, callback functions are implemented using function pointers.

What are callbacks?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

What is the purpose of callbacks?

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard." button.

How do you write a callback function in C?

Example Code #include<stdio. h> void my_function() { printf("This is a normal function."); } void my_callback_function(void (*ptr)()) { printf("This is callback function.


2 Answers

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.

like image 134
gehho Avatar answered Sep 21 '22 08:09

gehho


Any asynchronous action will rely on a callback.

like image 45
Gerrie Schenck Avatar answered Sep 20 '22 08:09

Gerrie Schenck