What is a callback?

前端 未结 11 1424
鱼传尺愫
鱼传尺愫 2020-11-28 00:57

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

11条回答
  •  悲&欢浪女
    2020-11-28 01:15

    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 callback)
        {
            callback("Hello world");
        }
    
        public void Test()
        {
            DoWork((result) => Console.WriteLine(result));
        }
    

提交回复
热议问题