您好,登錄后才能下訂單哦!
需要在.Net 4.0才會(huì)有Task
當(dāng)然,既然接觸到了Task,或許以后就不再用線程了,具體看情況了,之前幾個(gè)線程之間就發(fā)生了阻塞問題,這次就是要解決這個(gè)問題才下這個(gè)功夫的,否則寧可被差遣抱兒子尿尿去。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- namespace TaskDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Thread mTH = new Thread(RunTask);
- mTH.Start();
- //Thread mTH1 = new Thread(RunThread);
- //mTH1.Start();
- }
- private static void RunThread()
- {
- for (int i = 0; i < 20; i++)
- {
- Thread.Sleep(2);
- Console.WriteLine("RunThread{0}", i);
- }
- }
- private static void RunTask()
- {
- try
- {
- int mCount = 0;
- CancellationTokenSource tokenSource = new CancellationTokenSource();
- CancellationToken token = tokenSource.Token;
- Task t = new Task(() =>
- {
- Console.WriteLine("進(jìn)入任務(wù)……");
- Thread.Sleep(10);
- Console.WriteLine("任務(wù)開始工作……");
- //模擬工作過程
- for (int i = 0; i < 20; i++)
- {
- if (token.IsCancellationRequested == true)
- {
- break; //這里別人是用一個(gè)throw new OperationCanceledException(token); 但是我用就會(huì)報(bào)錯(cuò)
- }
- mCount++;
- Console.WriteLine("RunTask{0}", i);
- Thread.Sleep(1);
- }
- }, token);
- token.Register(() =>
- {
- Console.WriteLine("Canceled");
- });
- t.Start();
- Console.WriteLine("這條語(yǔ)句先運(yùn)行完畢了……");
- t.ContinueWith((task) =>
- {
- Console.WriteLine("任務(wù)完成,完成時(shí)候的狀態(tài)為:");
- Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}\tmCount={3}", task.IsCanceled, task.IsCompleted, task.IsFaulted, mCount);
- });
- Console.WriteLine("現(xiàn)在就按任意鍵的話,程序就退出了……");
- RunThread(); //線程內(nèi)部較耗時(shí)的測(cè)試
- Console.ReadKey(); //由于兩個(gè)sleep都有點(diǎn)時(shí)間,如果在這時(shí)間之前按下任意鍵,結(jié)果是程序提前終止了
- tokenSource.Cancel();
- Console.ReadKey(); //程序退出
- }
- catch (Exception Ex)
- {
- Console.WriteLine(Ex.Message);
- }
- }
- }
- }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。