Delegating a task in and getting notified when it completes (in C#)

前端 未结 7 884
灰色年华
灰色年华 2020-12-06 18:06

Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:


SomeMethod { // Member of AClass{}
            


        
7条回答
  •  甜味超标
    2020-12-06 18:21

    You have to use AsyncCallBacks. You can use AsyncCallBacks to specify a delegate to a method, and then specify CallBack Methods that get called once the execution of the target method completes.

    Here is a small Example, run and see it for yourself.

    class Program {

        public delegate void AsyncMethodCaller();
    
    
        public static void WorkerMethod()
        {
            Console.WriteLine("I am the first method that is called.");
            Thread.Sleep(5000);
            Console.WriteLine("Exiting from WorkerMethod.");
        }
    
        public static void SomeOtherMethod(IAsyncResult result)
        {
            Console.WriteLine("I am called after the Worker Method completes.");
        }
    
    
    
        static void Main(string[] args)
        {
            AsyncMethodCaller asyncCaller = new AsyncMethodCaller(WorkerMethod);
            AsyncCallback callBack = new AsyncCallback(SomeOtherMethod);
            IAsyncResult result = asyncCaller.BeginInvoke(callBack, null);
            Console.WriteLine("Worker method has been called.");
            Console.WriteLine("Waiting for all invocations to complete.");
            Console.Read();
    
        }
    }
    

提交回复
热议问题