需要在.Net 4.0才会有Task
当然,既然接触到了Task,或许以后就不再用线程了,具体看情况了,之前几个线程之间就发生了阻塞问题,这次就是要解决这个问题才下这个功夫的,否则宁可被差遣抱儿子尿尿去。
- 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();
-
-
-
- }
-
- 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("进入任务……");
- Thread.Sleep(10);
- Console.WriteLine("任务开始工作……");
-
- for (int i = 0; i < 20; i++)
- {
- if (token.IsCancellationRequested == true)
- {
- break;
- }
- mCount++;
- Console.WriteLine("RunTask{0}", i);
- Thread.Sleep(1);
- }
- }, token);
- token.Register(() =>
- {
- Console.WriteLine("Canceled");
-
- });
- t.Start();
- Console.WriteLine("这条语句先运行完毕了……");
- t.ContinueWith((task) =>
- {
- Console.WriteLine("任务完成,完成时候的状态为:");
- Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}\tmCount={3}", task.IsCanceled, task.IsCompleted, task.IsFaulted, mCount);
- });
- Console.WriteLine("现在就按任意键的话,程序就退出了……");
-
- RunThread();
-
- Console.ReadKey();
- tokenSource.Cancel();
- Console.ReadKey();
-
- }
- catch (Exception Ex)
- {
- Console.WriteLine(Ex.Message);
- }
- }
-
- }
- }
-
-
-
-