1. 程式人生 > >執行緒+委託+非同步

執行緒+委託+非同步

class Program
    {
        static void Main(string[] args)
        {
            //執行緒
            Thread tread = new Thread(new ThreadStart(new Action(() => { TestLock(); TestLock(); TestLock(); })));
            tread.Start();

            //執行緒
            new Task(() => { new Action(() => { TestLock(); }).BeginInvoke(null, null); }).Start();

            //非同步函式
            TestAsync();

            Console.Write("haha");
            Console.Read();
        }
        //委託1
        public delegate string TestDelegate(string a);

        /// <summary>
        /// 委託測試函式
        /// </summary>
        public static string TestDelegateMe(string a)
        {
            return a ?? "a為空顯示此語句!";
        }

        /// <summary>
        /// 委託
        /// </summary>
        public static void Delegate()
        {
            //BeginInvoke這種不會阻塞執行緒Invoke會阻塞

            //非同步委託1
            TestDelegate del = new TestDelegate(TestDelegateMe);
            string te = del.EndInvoke(del.BeginInvoke("a的值", null, null));

            //非同步委託2
            var action = new Action(() =>
            {
                TestLock();
            });
            action.EndInvoke(action.BeginInvoke(null, null));

            //執行緒+非同步委託3
            new Task(() =>
            {
                new Func<int>(() => { TestLock(); return 1; }).BeginInvoke(null, null);//執行緒非同步有返回
                new Action(() => { TestLock(); }).BeginInvoke(null, null);//執行緒非同步無返回
                TestLock();//執行緒同步
            }).Start();

            //執行緒
            Thread tread = new Thread(new ThreadStart(TestLock));
            tread.Start();

            HttpClient client = new HttpClient();
            client.PostAsync("", new MultipartFormDataContent() { new ByteArrayContent(System.Text.Encoding.Default.GetBytes("將要轉換為位元組的字串")) });

        }

        /// <summary>
        /// 非同步函式
        /// </summary>
        /// <returns>返回值只能是Task或者Task<T></returns>
        public static async void TestAsync()
        {
            await Task.Run(new Action(() => { TestLock(); }));
        }

        //資源鎖
        public static object obj = new object();

        /// <summary>
        /// 資源鎖的測試(用執行緒非同步呼叫此函式)
        /// </summary>
        public static void TestLock()
        {
            //當obj資源被鎖定,別的執行緒是無法呼叫的,所以必須等待此資源呼叫結束
            lock (obj)
            {
                for (int i = 0; i < 2; i++)
                {
                    Thread.Sleep(1000);
                    Console.Write(i);//輸出0-1/0-1
                }
            }
        }
  }