C#學習基類之_Task類

C#學習基類之_Task類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 基類練習_Task
{
    class Program
    {
        static void Main(string[] args)
        {
            #region MSDN上面的例子
            /*
            Action<object> action = (object obj) =>
              {
                  Console.WriteLine($"Task={Task.CurrentId},{obj},Thread={Thread.CurrentThread.ManagedThreadId}");
              };
            // create a task but do not start it.
            Task task1 = new Task(action, "alpha");

            //construct a started task
            Task task2 = Task.Factory.StartNew(action, "beta");
            task2.Wait();

            //launch t1
            task1.Start();
            Console.WriteLine($"t1 has been launched.Main thread={Thread.CurrentThread.ManagedThreadId}");

            //wait for task to finish
            task1.Wait();

            // construct a started task using Task.Run
            string taskData = "delta";
            Task task3 = Task.Run(() =>
            {
                Console.WriteLine($"Task={Task.CurrentId},obj={taskData},Thread={Thread.CurrentThread.ManagedThreadId}");
            });
            // wait for the task to finish
            task3.Wait();
            //constrcut an unstarted task
            Task task4 = new Task(action, "gamma");
            // run it unsynchronously
            task4.RunSynchronously();
            // Altough the task was run synchronously ,it is a good practice to wait for it in the event exceptions
            // were thrown bt the task
            task4.Wait();       
            */
            #endregion
            #region 我的例子
            Task task1 = new Task(() => { Console.WriteLine($"this is the first line.Thread Id={Thread.CurrentThread.ManagedThreadId}"); });
            task1.Start();
            task1.Wait();

            // task2
            Task task2= new Task(Method1);
            task2.Start();
           // task2.Wait();
            // the last line code
            Console.WriteLine($"This is the last line code. Thread Id={Thread.CurrentThread.ManagedThreadId}");

            #endregion


            Console.ReadKey();

        }
        public static void Method1()
        {
            for(int i=0;i<100;i++)
            {
                Console.WriteLine($"Thread Id={Thread.CurrentThread.ManagedThreadId},\t{i}");
            }
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章