您好,登錄后才能下訂單哦!
這篇文章主要介紹“C#異步編程Task怎么創(chuàng)建”,在日常操作中,相信很多人在C#異步編程Task怎么創(chuàng)建問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C#異步編程Task怎么創(chuàng)建”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
ThreadPool相比Thread來說具備了很多優(yōu)勢,但是ThreadPool卻又存在一些使用上的不方便。比如:
Task支持線程的取消、完成、失敗通知等交互性操作,但是ThreadPool不支持;
Task支持線程執(zhí)行的先后次序,但是ThreadPool不支持;;
以往,如果開發(fā)者要實現(xiàn)上述功能,需要完成很多額外的工作,現(xiàn)在,F(xiàn)CL中提供了一個功能更強大的概念:Task。Task在線程池的基礎(chǔ)上進行了優(yōu)化,并提供了更多的API。在FCL4.0中,如果我們要編寫多線程程序,Task顯然已經(jīng)優(yōu)于傳統(tǒng)的方式。
Task t = new Task(() => { Console.WriteLine("Start……"); //模擬工作過程 Thread.Sleep(5000); }); t.Start(); t.ContinueWith((task) => { Console.WriteLine("Already Finished,States:"); Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted); }); Console.ReadKey();
線程引用方法:
static void TaskMethod(string name) { Console.WriteLine("Task: {0} is running on a thread id {1}. Is thread pool thread: {2}", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); }
//方式一 var t1 = new Task(() => TaskMethod("Task_1")); t1.Start(); //等待所有任務(wù)結(jié)束 //任務(wù)的狀態(tài): //Start之前為:Created //Start之后為:WaitingToRun Task.WaitAll(t1);////等待所有任務(wù)結(jié)束
//方式二 Task.Run(() => TaskMethod("Task_2"));
//方式三 Task.Factory.StartNew(() => TaskMethod("Task_3")); //直接異步的方法 //或者 var t3 = Task.Factory.StartNew(() => TaskMethod("Task_3")); Task.WaitAll(t3);//等待所有任務(wù)結(jié)束 //任務(wù)的狀態(tài) //Start之前為:Running //Start之后為:Running
實例:
class Program { static void Main(string[] args) { var t1 = new Task(() => TaskMethod("Task_1")); var t2 = new Task(() => TaskMethod("Task_2")); t2.Start(); t1.Start(); Task.WaitAll(t1, t2); Task.Run(() => TaskMethod("Task_3")); Task.Factory.StartNew(() => TaskMethod("Task_4")); //標記為長時間運行任務(wù),則任務(wù)不會使用線程池,而在單獨的線程中運行。 Task.Factory.StartNew(() => TaskMethod("Task_5"), TaskCreationOptions.LongRunning); #region 常規(guī)的使用方式 Console.WriteLine("主線程執(zhí)行業(yè)務(wù)處理."); //創(chuàng)建任務(wù) Task task = new Task(() => { Console.WriteLine("使用System.Threading.Tasks.Task執(zhí)行異步操作."); for (int i = 0; i < 10; i++) { Console.WriteLine(i); } }); //啟動任務(wù),并安排到當前任務(wù)隊列線程中執(zhí)行任務(wù)(System.Threading.Tasks.TaskScheduler) task.Start(); Console.WriteLine("主線程執(zhí)行其他處理"); task.Wait(); #endregion Thread.Sleep(TimeSpan.FromSeconds(1)); Console.ReadLine(); } static void TaskMethod(string name) { Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); } }
結(jié)果:
class Program { async static void AsyncFunction() { await Task.Delay(1); Console.WriteLine("使用System.Threading.Tasks.Task執(zhí)行異步操作."); for (int i = 0; i < 10; i++) { Console.WriteLine(string.Format("AsyncFunction:i={0}", i)); } } public static void Main() { Console.WriteLine("主線程執(zhí)行業(yè)務(wù)處理."); AsyncFunction(); Console.WriteLine("主線程執(zhí)行其他處理"); for (int i = 0; i < 10; i++) { Console.WriteLine(string.Format("Main:i={0}", i)); } Console.ReadLine(); } }
結(jié)果:
static Task<int> CreateTask(string name) { return new Task<int>(() => TaskMethod1(name)); }
static int TaskMethod1(string name) { Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan.FromSeconds(2)); return 42; }
//方式四 Task<int> task = CreateTask("Task_1"); task.Start(); int result = task.Result;
實例:
class Program { static Task<int> CreateTask(string name) { return new Task<int>(() => TaskMethod(name)); } static void Main(string[] args) { TaskMethod("Main Thread Task"); Task<int> task = CreateTask("Task_1"); task.Start(); int result = task.Result; Console.WriteLine("Task_1 Result is: {0}", result); task = CreateTask("Task_2"); //該任務(wù)會運行在主線程中 task.RunSynchronously(); result = task.Result; Console.WriteLine("Task_2 Result is: {0}", result); task = CreateTask("Task_3"); Console.WriteLine(task.Status); task.Start(); while (!task.IsCompleted) { Console.WriteLine(task.Status); Thread.Sleep(TimeSpan.FromSeconds(0.5)); } Console.WriteLine(task.Status); result = task.Result; Console.WriteLine("Task_3 Result is: {0}", result); #region 常規(guī)使用方式 //創(chuàng)建任務(wù) Task<int> getsumtask = new Task<int>(() => Getsum()); //啟動任務(wù),并安排到當前任務(wù)隊列線程中執(zhí)行任務(wù)(System.Threading.Tasks.TaskScheduler) getsumtask.Start(); Console.WriteLine("主線程執(zhí)行其他處理"); //等待任務(wù)的完成執(zhí)行過程。 getsumtask.Wait(); //獲得任務(wù)的執(zhí)行結(jié)果 Console.WriteLine("任務(wù)執(zhí)行結(jié)果:{0}", getsumtask.Result.ToString()); Console.ReadLine(); #endregion } static int TaskMethod(string name) { Console.WriteLine("Task: {0} is running on a thread id {1}. Is thread pool thread: {2}", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan.FromSeconds(2)); return 42; } static int Getsum() { int sum = 0; Console.WriteLine("使用Task執(zhí)行異步操作."); for (int i = 0; i < 100; i++) { sum += i; } return sum; } }
結(jié)果:
class Program { public static void Main() { var ret1 = AsyncGetsum(); Console.WriteLine("主線程執(zhí)行其他處理"); for (int i = 1; i <= 3; i++) Console.WriteLine("Call Main()"); int result = ret1.Result; //阻塞主線程 Console.WriteLine("任務(wù)執(zhí)行結(jié)果:{0}", result); Console.ReadLine(); } async static Task<int> AsyncGetsum() { await Task.Delay(1); int sum = 0; Console.WriteLine("使用Task執(zhí)行異步操作."); for (int i = 0; i < 100; i++) { sum += i; } return sum; } }
結(jié)果:
到此,關(guān)于“C#異步編程Task怎么創(chuàng)建”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。