using System; using System.Threading; using System.Runtime.Remoting.Messaging; namespace AsyncCallbackTest { public delegate String FixByItselfDelegate(String part); class Program { public static void Main(String[] args) { Car myCar = new Car(); FixByItselfDelegate d = new FixByItselfDelegate(myCar.FixByItself); AsyncCallback oCallback = new AsyncCallback(myCar.FixCompleted); d.BeginInvoke("Engine", oCallback, null); Console.WriteLine("Method is called asyncronously in {0}", Thread.CurrentThread.GetHashCode()); Thread.Sleep(5000); // Thread will wait for 5 seconds. Console.WriteLine(Thread.CurrentThread.GetHashCode() + " Thread is ended. Press enter,please."); Console.ReadLine(); } } public class Car { public String Name; public String ProductYear; public String FixByItself(String part) { Console.WriteLine("Now Fixing {0} in Thread {1}", part, Thread.CurrentThread.GetHashCode()); Thread.Sleep(3000); // Thread will wait for 3 seconds. return "Fixing " + part + " is completed"; } public void FixCompleted(IAsyncResult ar) { AsyncResult AR = (AsyncResult)ar; FixByItselfDelegate d = (FixByItselfDelegate)AR.AsyncDelegate; // ar을 FixByItselfDelegate로 변환 후 String strResult = d.EndInvoke(ar); // EndInvoke로 return 값을 읽어온다. Console.WriteLine(strResult); } } }
C#에서 비동기적으로 메소드를 호출하는 방법이다.
리턴값이 필요한 경우에는 델리게이트명.BeginInvoke를 호출할 때 두번째 인수로 AsyncCallback 개체를 넘겨주면 된다. 이 메소드 안에서 IAsyncResult 객체를 비동기적으로 호출한 메소드에 대한 델리게이트로 변환한 후 EndInvoke를 호출하면 Return 값을 얻어올 수 있다.