Delegates and Callbacks

后端 未结 4 946
有刺的猬
有刺的猬 2021-02-03 14:07

Does the term callback in the context of delegates mean ,\"a delegate delegating it works to another delegate inorder to finish some task\" ?

Example :(

相关标签:
4条回答
  • 2021-02-03 14:21

    This will get down voted precisely for the reason it is correct. C# does not implement delegates, what it implements is call forwarding. This incorrect use of nomenclature is probably the biggest problem with C# in this regard.

    The ACM paper below is the first description of what later would be called a delegate. Basically a delegate is something that appears to be an instance of an object (how it is actually implemented is irrelevant). This means that you can call methods, access properties, etc. from the delegate.

    http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html

    What C# implements is callbacks or call-forwarding (all dependent on how you use them). These are not delegates. In order to be a delegate one be able to access the object as if it were the object itself.

    When a pen delegates a draw message to a prototypical pen, it is saying “I don’t know how to handle the draw message. I’d like you to answer it for me if you can, but if you have any further questions, like what is the value of my x variable, or need anything done, you should come back to me and ask.” If the message is delegated further, all questions about the values of variables or requests to reply to messages are all inferred to the object that delegated the message in the first place. - Henry Lieberman

    So, how did it get messed up? To be honest, I don't know. I DO know that I've been using delegates (over 16 years now) long before C# and what C# implements are not delegates.

    A really good explanation can be had here.

    http://www.saturnflyer.com/blog/jim/2012/07/06/the-gang-of-four-is-wrong-and-you-dont-understand-delegation/

    Real delegation is more than creating callbacks or call forwarding. A real delegate lets me call any method on that object, get and/or set public properties, etc - all as if it was the object itself. This is far more powerful, and actually easier to use, than the C# "delegation".

    The OP asked:

    Does the term callback in the context of delegates mean ,"a delegate delegating it works to another delegate inorder to finish some task" ?

    The answer to this is yes. A callback in the context of delegates can can only be used to finish up some task. For example, you have a class that get's data from a weather site. Since it is non-deterministic, implementing a callback when the data has been received (and perhaps parsed) would be spiffy.

    As to why delegation was corrupted, I've no idea. I look forward to C# implementing TRUE delegation.

    0 讨论(0)
  • 2021-02-03 14:24

    A callback is what the delegate executes when it is invoked. For example, when using the Asynchronous pattern using delegates, you would do something like this:

    public static void Main(string[] args)
    {
        Socket s = new Socket(...);
    
        byte[] buffer = new byte[10];
        s.BeginReceive(buffer, 0, 10, SocketFlags.None, new AsyncCallback(OnMessageReceived), buffer);
    
        Console.ReadKey();
    }
    
    public static void OnMessageReceived(IAsyncResult result)
    {
        // ...
    }
    

    OnMessageReceived is the callback, the code that is executed by invoking the delegate. See this Wikipedia article for some more information, or Google some more examples.

    0 讨论(0)
  • 2021-02-03 14:27

    Your example is a good start, but it is incorrect. You don't make a new delegate in the method, it's used in the declaration of an event in the class. See this modified example of your code:

    namespace Test
    {
        //In this case, this delegate declaration is like specifying a specific kind of function that must be used with events.
        public delegate string CallbackDemo(string str);
        class Program
        {
            public static event CallbackDemo OnFoobared;
            static void Main(string[] args)
            {
                //this means that StrAnother is "subscribing" to the event, in other words it gets called when the event is fired
                OnFoobared += StrAnother;
                string substr = Strfunc();
                Console.WriteLine(substr);
                Console.ReadKey(true);
                //this is the other use of delegates, in this case they are being used as an "anonymous function". 
                //This one takes no parameters and returns void, and it's equivalent to the function declaration 
                //'void myMethod() { Console.WriteLine("another use of a delegate"); }'
                Action myCode = delegate
                {
                    Console.WriteLine("another use of a delegate");
                };
                myCode();
                Console.ReadKey(true);
                //the previous 4 lines are equivalent to the following however this is generally what you should use if you can
                //its called a lambda expression but it's basically a way to toss arbitrary code around
                //read more at http://www.developer.com/net/csharp/article.php/3598381/The-New-Lambda-Expressions-Feature-in-C-30.htm or 
                //http://stackoverflow.com/questions/167343/c-lambda-expression-why-should-i-use-this
                Action myCode2 = () => Console.WriteLine("a lambda expression");
                myCode2();
                Console.ReadKey(true);
            }
    
            static string Strfunc()
            {
                return OnFoobared("a use of a delegate (with an event)");
            }
            static string StrAnother(string str)
            {
                return str.Substring(1, 3).ToString();
            }
        }
    }
    

    I've only scratched the surface here; search stack overflow for "delegate c#" and "lambda expression c#" for lots more!

    0 讨论(0)
  • 2021-02-03 14:37

    A callback is basically a delegate passed into a procedure which that procedure will "call back" at some appropriate point. For example, in asynchronous calls such as WebRequest.BeginGetResponse or a WCF BeginXxx operation, you'd pass an AsyncCallback. The worker will "call back" whatever method you pass in as the AsyncCallback, in this case when it's finished to let you know that it's finished and to obtain the result.

    An event handler could be considered another example. For example, when you attach a handler to a Click event, the button will "call back" to that handler when the click occurs.

    0 讨论(0)
提交回复
热议问题