static void Main(string[] args) { try { // Display a message to show we're in Main(). Console.WriteLine("Starting the program."); // Get the number of milliseconds from the arguments // passed in from the command line. int milliseconds = GetMilliseconds(args[0]); // Create the ComplicatedCalculator object. ComplicatedCalculator cc = new ComplicatedCalculator(milliseconds); // Create the delegate object. DoSomething method = new DoSomething(cc.CalculateValue); // Call the delegate asynchronously. IAsyncResult asynchStatus = method.BeginInvoke(10.4, 7.451, null, null); // Call WaitOne() to wait until the async task is done. Console.WriteLine("\nWaiting for task to complete."); // Include a timeout and check to see if it completed in time. bool inTimeBool = asynchStatus.AsyncWaitHandle.WaitOne(10000); if (inTimeBool) { Console.WriteLine("\nTask has completed."); // Get the result of the asynchronous call. double results = method.EndInvoke(asynchStatus); // Display the results. Console.WriteLine("\nThe result is: {0}", results); } else { Console.WriteLine("\nTask did NOT complete in time. There are no results. May need to stop application running using Task Manager."); } } catch (Exception e) { Console.WriteLine("\nEXCEPTION: {0}.", e.Message); } // Pause so we can look at the console window. Console.Write("\n\nPress <ENTER> to end: "); Console.ReadLine(); }
static void Main(string[] args) { //1.实例化一个委托,调用者发送一个请求,请求执行该方法体(还未执行) DoSomething doSomething = new DoSomething( () => { Console.WriteLine("如果委托使用 beginInvoke 的话,这里便是异步方法体"); //4,实现完这个方法体后自动触发下面的回调函数方法体 } ); //3 。调用者(主线程)去触发异步调用,采用异步的方式请求上面的方法体 IAsyncResult result = doSomething.BeginInvoke( //2.自定义上面方法体执行后的回调函数 new AsyncCallback ( //5.以下是回调函数方法体 //asyncResult.AsyncState其实就是AsyncCallback委托中的第二个参数 asyncResult => { doSomething.EndInvoke(asyncResult); Console.WriteLine(asyncResult.AsyncState.ToString()); } ), "AsyncResult.AsyncState" ); //DoSomething......调用者(主线程)会去做自己的事情 Console.ReadKey(); }
private void btnAsnyc_Click(object sender, EventArgs e) { //实例化一个委托 //DoSomething dosomething = new DoSomething(t => Console.WriteLine("这里是异步调用,str是{0}",t)); //DoSomething dosomething =t => Console.WriteLine("这里是btnAsnyc_Click,str是{0},当前线程Id:{1}", t,Thread.CurrentThread.ManagedThreadId); //dosomething("直接调用");//主线程调用 //dosomething.Invoke("Invoke调用");//主线程调用 //dosomething.BeginInvoke("BeginInvoke调用", null, null);//这就是异步调用 子线程在调用 Console.WriteLine("**************btnAsnyc_Click异步开始******************"); DoSomething todo = DoSomethingTest; for (int i = 0; i < 5; i++) { todo.BeginInvoke(string.Format("btnAsnyc_Click异步"), null, null);//BeginInvoke 该方法就是一个异步执行的方法,会调用一个子线程 } Console.WriteLine("**************btnAsnyc_Click异步结束******************"); /***************总结异步的特点******************* * 1.同步会卡住界面,异步不会;原因:异步启动了子线程,主线程得到释放; * 2.同步方法会慢,异步方法会快,但是消耗的资源比较多,因为启动了多个子线程; * 3.异步线程启动是无序的,结束也是无序的,由操作系统决定; * *****************总结异步的特点***********/ }
static void Main(string[] args) { Console.WriteLine("这是主线程 ID:" + Thread.CurrentThread.ManagedThreadId); //无参无返回值 DoSomething doSomething = Method1; doSomething.BeginInvoke(null, null); //无参有返回值 DoSomethingReturn doSomethingReturn = Method2; IAsyncResult iasyncResult = doSomethingReturn.BeginInvoke(null, null); int result = doSomethingReturn.EndInvoke(iasyncResult);//要获取委托的返回值,必须等待子线程执行结束 //有参无返回值 DoMore doMore = Method3; doMore.BeginInvoke(16, "guo", null, null); //有参有返回值 DoMoreReturn doMoreReturn = Method4; IAsyncResult iasyncResult2 = doMoreReturn.BeginInvoke(16, "guo", null, null); int result2 = doMoreReturn.EndInvoke(iasyncResult2);//要获取委托的返回值,必须等待子线程执行结束 //异步回调 DoMoreReturn doMoreReturn2 = Method4; doMoreReturn2.BeginInvoke(16, "guo", Callback, "wulala"); Console.ReadKey(); }
static void Main(string[] args) { try { // Display a message to show we're in Main(). Console.WriteLine("Starting the program."); // Get the number of milliseconds from the arguments // passed in from the command line. int milliseconds = GetMilliseconds(args[0]); // Create the ComplicatedCalculator object. ComplicatedCalculator cc = new ComplicatedCalculator(milliseconds); // Create the delegate object. DoSomething method = new DoSomething(cc.CalculateValue); // Call the delegate asynchronously. IAsyncResult asynchStatus = method.BeginInvoke(10.4, 7.451, null, null); // Poll to see if the asynchronous call is done. while (!asynchStatus.IsCompleted) { System.Threading.Thread.Sleep(750); Console.WriteLine ("\nSeeing if the asynch call is done."); } // Get the result of the asynchronous call. double results = method.EndInvoke(asynchStatus); // Display the results. Console.WriteLine("\nThe result is: {0}", results); } catch (Exception e) { Console.WriteLine("\nEXCEPTION: {0}.", e.Message); } // Pause so we can look at the console window. Console.Write("\n\nPress <ENTER> to end: "); Console.ReadLine(); }
static void Main(string[] args) { try { // Display a message to show we're in Main(). Console.WriteLine("Starting the program."); // Get the number of milliseconds from the arguments // passed in from the command line. int milliseconds = GetMilliseconds(args[0]); // Create the ComplicatedCalculator object. ComplicatedCalculator cc = new ComplicatedCalculator(milliseconds); // Create the delegate object. DoSomething method = new DoSomething(cc.CalculateValue); // Create the callback delegate. AsyncCallback callbackMethod = new AsyncCallback(ComputationComplete); // Create a string that will be displayed in the // callback method. string thanksString = "Main() is very happy now!"; // Call the delegate asynchronously. IAsyncResult asynchStatus = method.BeginInvoke (10.4, 7.451, callbackMethod, thanksString); // Display some messages to show that Main() is still // responsive while the calculation is going on. Console.WriteLine("\nNow I'm going to go do something else."); System.Threading.Thread.Sleep(1500); Console.WriteLine("Like talk about the weather."); System.Threading.Thread.Sleep(1500); Console.WriteLine("Or the latest news."); System.Threading.Thread.Sleep(1500); Console.WriteLine("You know, my foot hurts."); System.Threading.Thread.Sleep(1500); Console.WriteLine("I love hotdogs!"); System.Threading.Thread.Sleep(1500); Console.WriteLine("How much is a shake at Burgermaster?"); System.Threading.Thread.Sleep(1500); Console.WriteLine("Ok, now I'm getting hungry!"); System.Threading.Thread.Sleep(1500); } catch (Exception e) { Console.WriteLine("\nEXCEPTION: {0}.", e.Message); } // Pause so we can look at the console window. Console.Write("\n\nPress <ENTER> to end: "); Console.ReadLine(); }