簡單的非同步編程入門例子

來源:互聯網
上載者:User
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace 非同步編程例子{    class Program    {        public delegate int CaculateDelegate(int min, int max);        static void Main(string[] args)        {            CaculateDelegate d=Caculate;            Console.WriteLine("請輸入:");            int min = int.Parse(Console.ReadLine());            Console.WriteLine("請輸入");            int max = int.Parse(Console.ReadLine());            IAsyncResult ret = d.BeginInvoke(min,max,null,null);            Console.WriteLine("正在計算中,請耐心等待.....");              while (!ret.IsCompleted)            {                Console.Write(".");                Thread.Sleep(1000);            }            int count = (int)d.EndInvoke(ret);            Console.WriteLine();            Console.WriteLine("{0}+{1}={2}",min,max,count);            Console.ReadKey();        }        public static int Caculate(int min, int max)        {            int count;            Thread.Sleep(5000);            count = min + max;            return count;        }    }}

上例使用輪詢方法不斷詢問非同步呼叫是否完成,會浪費不少CPU時間在迴圈等待上,下例可以讓非同步呼叫方法在結束時自動調用一個函數,並在這個函數中顯示處理結果。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace 非同步編程例子{    class Program    {        public delegate int CaculateDelegate(int min, int max);        public static CaculateDelegate d = Caculate;        static void Main(string[] args)        {            Console.WriteLine("請輸入:");            int min = int.Parse(Console.ReadLine());            Console.WriteLine("請輸入");            int max = int.Parse(Console.ReadLine());            IAsyncResult ret = d.BeginInvoke(min,max,ShowResult,(min+","+max));            Console.WriteLine("正在計算中,請耐心等待.....");            Console.ReadKey();        }        public static int Caculate(int min, int max)        {            int count;            Thread.Sleep(5000);            count = min + max;            return count;        }        public static void ShowResult(IAsyncResult ret)        {            int count = (int)d.EndInvoke(ret);              string[] n = ((string)ret.AsyncState).Split(',');            Console.WriteLine();            Console.WriteLine("{0}+{1}={2}", n[0],n[1], count);        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.