C#5.0 非同步編程

來源:互聯網
上載者:User

標籤:fun   void   封裝   ...   封裝   call   span   runas   ide   

委託的BeginInvoke實現非同步

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace ConsoleApplication1{    public delegate int MyDelegate(int x);    class Program    {        static void Main(string[] args)        {            MyDelegate del = new MyDelegate((a) =>            {                Console.WriteLine("Sub Thread Begin");                Thread.Sleep(2000);                return 1;            });            //delegate的BeginInvoke方法實現非同步呼叫            del.BeginInvoke(1, (a) => { Console.WriteLine("Sub Thread Callback"); }, null);            Console.WriteLine("Main Thread Over");            Console.Read();        }    }}
delegate的BeginInvoke

C#5.0 Async函數線性編程 方式實現非同步編程

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("Main Thread Begin");            MyFunc();            Console.WriteLine("Main Thread Over");            Console.Read();        }        static async void MyFunc()        {            Console.WriteLine("MyFunc Begin");            //程式執行到這裡開啟非同步任務            await Task.Run(() =>            {                Console.WriteLine("耗時操作開始");                Thread.Sleep(2000);                Console.WriteLine("耗時操作結束");            });            Console.WriteLine("MyFunc Over");        }    }}
C#5.0非同步函數

C#5.0 Async函數封裝方法

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("Main Thread Begin");            new TestClass().DisplayResult();            Console.WriteLine("Main Thread Over");            Console.Read();        }    }    class TestClass    {        public async void DisplayResult()        {            Console.WriteLine("耗時操作開始");            //在非同步函數中非同步呼叫封裝為Task的函數            int res = await GetResultAsync(2);            Console.WriteLine(res);            Console.WriteLine("耗時操作結束");        }        //將耗時操作封裝到Task函數中        public Task<int> GetResultAsync(int n)        {            return Task.Run(() =>            {                Thread.Sleep(3000);                return n + 1;            });        }    }}
C#5.0非同步函數

封裝函數非同步執行

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("Main Thread Begin");            TaskAsyncHelper.RunAsync(new Func<int, int>(MyFunc), new Action<int>(DisplayResult), 2);            Console.WriteLine("Main Thread Over");            Console.Read();        }        static int MyFunc(int i)        {            Console.WriteLine("耗時操作開始");            Thread.Sleep(3000);            return i + 10;        }        static void DisplayResult(int i)        {            Console.WriteLine("結果是:" + i);            Console.WriteLine("耗時操作結束");        }    }    //封裝共通函數,傳入函數後和回呼函數後非同步執行    public static class TaskAsyncHelper    {        public static async void RunAsync<TResult>(Func<int, TResult> function, Action<TResult> callback, int num)        {            //將傳入的函數封裝為Task            Func<Task<TResult>> taskFunc = () =>            {                return Task.Run(() =>                {                    return function(num);                });            };            //非同步執行封裝的Task            TResult res = await taskFunc();            if (callback != null)            {                callback(res);            }        }    }}
把傳入的函數封裝為非同步執行

訊號量控制線程數量

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace ConsoleApplication1{    class Program    {        //聲明訊號量,表示同一資源最大線程數是3        static SemaphoreSlim semLim = new SemaphoreSlim(3);        static void Main(string[] args)        {            Console.WriteLine("Main Thread Begin");            for (int i = 0; i < 20; i++)            {                new Thread(SemaphoreTest).Start();            }            Console.WriteLine("Main Thread Over");            Console.Read();        }        static void SemaphoreTest()        {            semLim.Wait(); //阻塞當前線程,直到訊號量釋放            Console.WriteLine("線程"+Thread.CurrentThread.ManagedThreadId.ToString()+"執行開始...");            Thread.Sleep(2000);            Console.WriteLine("線程" + Thread.CurrentThread.ManagedThreadId.ToString() + "執行結束...");            semLim.Release();//釋放訊號量        }    }}
訊號量控制線程數

 

C#5.0 非同步編程

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.