다음을 통해 공유


Asynchronous method call in C#

*If you want to call a method that will perform some operations in background and you want to proceed with performing other operations while background operation is happening, you can call the method asynchronously to execute it in background. *

* *The code sample includes a console application Program.cs class and a separate class called DemoAsyncMethodCall.cs.

Program.cs class consist of the code to call and demonstrate the behavious of the solution.

DemoAsyncMethodCall.cs class consist of the code with asynchronous method call. A sample method named Capture is created which is a static method which makes asyn call to the saveData method. Save data method can perform long running operation whatever is need to run in background.

 

Below is the sample code, the entire running code is attached herewith the sample, you can download and directly run it from Visual Studio

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 
  
namespace ConsoleApplication1 
{ 
    class Program 
    { 
        static void  Main(string[] args) 
        { 
            MethodA(); 
  
            Console.ReadKey(); 
        } 
  
        private static  void MethodA() 
        { 
            Console.WriteLine("Method A Execution Started"); 
  
            DemoAsyncMethodCall.Capture("Call from Method A"); 
  
            MethodB(); 
  
            Console.WriteLine("Method A completed"); 
  
        } 
  
        private static  void MethodB() 
        { 
            Console.WriteLine("Inside Method B"); 
        } 
    } 
}
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 
using System.Threading;  
  
namespace ConsoleApplication1 
{ 
    public class  DemoAsyncMethodCall 
    { 
        delegate void  MethodDelegate(string message); 
          
        public static  void Capture(string message) 
        { 
            MethodDelegate dlgt = new  MethodDelegate(saveData); 
  
            IAsyncResult ar = dlgt.BeginInvoke(message, null, null); 
        } 
          
        private static  void saveData(string message) 
        { 
            Console.WriteLine("Aync method call saveData with message: " + message); 
        } 
                  
    } 
}

Download Sample Code:
http://code.msdn.microsoft.com/Sample-code-for-asynchronou-130e2c56

Reference:
http://shaikhnizam.blogspot.in/2014/01/how-to-make-asynchronous-method-call-in.html

See Also