参考资料:
https://www.cnblogs.com/scmail81/archive/2018/08/20/9508448.html
https://www.cnblogs.com/qiandi/p/4704255.html
https://www.cnblogs.com/dudu/archive/2018/10/24/task-yield.html(Task.Yield的用途)
https://www.cnblogs.com/yunfeifei/p/4122084.html(看一下“Task和线程池之间的抉择”就可以了)
https://www.cnblogs.com/zeroone/p/5246525.html(Task.Run VS Task.Factory.StratNew)
https://www.cnblogs.com/majiang/p/7908001.html(相关底层实现)
以下为本人调试时的代码(比较多):
代码1:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Task的用法
{
//简单示例
class Program
{
static void Main(string[] args)
{
Task t = new Task(() =>
{
Console.WriteLine("任务开始工作 。 。 。");
Thread.Sleep(5000);
});
t.Start();
t.ContinueWith((task) =>
{
Console.WriteLine("t.Id = " + t.Id + ",task.Id = " + task.Id);//task就是t
Console.WriteLine("任务完成,完成时候的状态为:");
Console.WriteLine("IsCanceled = " + task.IsCanceled + "," + "IsCompleted = " + task.IsCompleted + "," + "IsFaulted = " + task.IsFaulted + "," + "IsThreadPoolThread = " + Thread.CurrentThread.IsThreadPoolThread);
});
Console.ReadLine();
}
}
}
代码2:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 创建任务_无返回值
{
//无返回值的方式创建任务
class Program
{
static void Main(string[] args)
{
var t1 = new Task(() => TaskMethod("Task 1"));//方式1,任务的状态在start之前为Created,start之后为WaitingToRun
var t2 = new Task(() => TaskMethod("Task 2"));
t2.Start();
Console.WriteLine("t1在strat之前的状态为" + t1.Status);
t1.Start();
Console.WriteLine("t1在strat之后的状态为" + t1.Status);
Task.WaitAll(t1,t2);
var t3 = Task.Run(() => TaskMethod("Task 3"));//方式2
Console.WriteLine("t3的状态为" + t3.Status);
var t4 = Task.Factory.StartNew(() => TaskMethod("Task 4"));//方式3
Console.WriteLine("t4的状态为" + t4.Status);
Task.Factory.StartNew(() => TaskMethod("Task 5"),TaskCreationOptions.LongRunning);//标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。
#region 常规的使用方式
Console.WriteLine("主线程执行业务处理");
//创建任务
Task task = new Task(() =>
{
Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
});
//启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
task.Start();
Console.WriteLine("主线程执行其他处理");
task.Wait();
#endregion
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.ReadLine();
}
static void TaskMethod(string name)
{
Console.WriteLine(name + " is running on a thread id " + Thread.CurrentThread.ManagedThreadId + " . Is threadPool thread : " + Thread.CurrentThread.IsThreadPoolThread);
}
}
}
代码3:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 通过async和await实现无返回值任务
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff" + " 主线程执行业务处理"));
AsyncFunction();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 主线程执行其他处理");
for (int i = 101; i <= 110; i++)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Main : i = " + i);
}
Console.ReadLine();
}
async static void AsyncFunction()
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
await Task.Delay(100);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 使用System.Threading.Tasks.Task执行异步操作");
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " AsyncFunction : i = " + i);
}
}
}
}
代码4:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 创建任务_带返回值
{
class Program
{
static void Main(string[] args)
{
TaskMethod("Main Thread Task");
Task task = CreateTask("Task 1");
task.Start();
int result = task.Result;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task 1 Result is " + result);
task = CreateTask("Task 2");
task.RunSynchronously();//该任务会运行在主线程中
result = task.Result;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task 2 Result is " + result);
task = CreateTask("Task 3");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status.ToString());
task.Start();
while (!task.IsCompleted)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status.ToString());
Thread.Sleep(50);
}
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status.ToString());
result = task.Result;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task 3 Result is " + result);
#region 常规使用方式
//创建任务
Task getSumTask = new Task(() => GetSum());
//启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
getSumTask.Start();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 主线程执行其他处理");
//等待任务的完成执行过程
getSumTask.Wait();
//获得任务的执行结果
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 任务结果:" + getSumTask.Result);
#endregion
Console.ReadLine();
}
static int TaskMethod(string name)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + name + " is running on a thread id : " + Thread.CurrentThread.ManagedThreadId + " , Is ThreadPool : " + Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(200);
return 911;
}
static int GetSum()
{
int sum = 0;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 使用Task执行异步操作");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
}
static Task CreateTask(string name)
{
return new Task(() => TaskMethod(name));
}
}
}
代码5:
using System;
using System.Threading.Tasks;
namespace 通过async和await实现带返回值任务
{
class Program
{
static void Main(string[] args)
{
var ret = AsyncGetSum();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 主线程执行其他处理");
for (int i = 1; i <= 3; i++)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + i);
}
int result = ret.Result;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 任务执行结果:" + result);
Console.ReadLine();
}
async static Task AsyncGetSum()
{
await Task.Delay(500);
int sum = 0;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 使用Task执行异步操作");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
}
}
}
代码6:
using System;
using System.Threading.Tasks;
namespace 创建任务_带参数_带返回值
{
class Program
{
static void Main(string[] args)
{
object para = 911;
Func
代码7:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 通过async和await实现带返回值带参数的任务
{
class Program
{
static void Main(string[] args)
{
object obj = "123456";
var task = AsyncFunction(obj);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Main");
string result = task.Result;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " AsyncFunction:" + result);
Console.ReadLine();
}
async static Task AsyncFunction(object obj)
{
await Task.Delay(500);
return "obj = " + obj;
}
}
}
代码8:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 组合任务
{
class Program
{
static void Main(string[] args)
{
//创建一个任务
Task task = new Task(() =>
{
int sum = 0;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 使用Task执行异步操作");
for (int i = 0; i < 100; i++)
{
sum += i;
Thread.Sleep(10);
}
return sum;
});
//启动任务,并安排到当前任务队列线程中执行(System.Threading.Tasks.TaskScheduler)
task.Start();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 主线程执行其他处理");
//任务完成时执行处理
Task task2 = task.ContinueWith((t) =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " *** task2 *** ");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 任务完成后的执行结果:" + t.Result);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " +++ task2 +++ ");
});
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ==============================");
task.Wait();
task2.Wait();
Console.ReadLine();
}
}
}
代码9:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace 串行任务
{
class Program
{
static void Main(string[] args)
{
//表示线程安全的后进先出(LIFO)集合
ConcurrentStack stack = new ConcurrentStack();
//t1串行
var t1 = Task.Factory.StartNew(() =>
{
stack.Push(1);
stack.Push(2);
});
//t2,t3并行执行
var t2 = t1.ContinueWith((t) =>
{
int result;
stack.TryPop(out result);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task t2 result = " + result + ", Thread Id : " + Thread.CurrentThread.ManagedThreadId);
});
//t2,t3并行执行
var t3 = t1.ContinueWith((t) =>
{
int result;
stack.TryPop(out result);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task t3 result = " + result + ", Thread Id : " + Thread.CurrentThread.ManagedThreadId);
});
//等待t2和t3执行完
Task.WaitAll(t2,t3);
//t4串行执行
var t4 = Task.Factory.StartNew(() =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 当前集合元素个数:" + stack.Count + ", Thread Id : " + Thread.CurrentThread.ManagedThreadId);
});
t4.Wait();
Console.ReadLine();
}
}
}
代码10:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 子任务
{
class Program
{
static void Main(string[] args)
{
Task parentTask = new Task(state =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + state);
string[] result = new string[2];
//创建并启动子任务
new Task(() =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 子任务1");
result[0] = "我是子任务1";
Thread.Sleep(100);
},TaskCreationOptions.AttachedToParent).Start();//此处的TaskCreationOptions.AttacedToParent可以使子任务附加到父任务,这样在parentTask.ContinueWith中的任务要等到子任务完成才能执行。
new Task(() =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 子任务2");
result[1] = "我是子任务2";
Thread.Sleep(2000);
},TaskCreationOptions.AttachedToParent).Start();
return result;
},"我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会执行。");
//任务处理完成后执行的操作
parentTask.ContinueWith((t) =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ContinueWith start");
Array.ForEach(t.Result, (r) =>
{
Console.WriteLine(r);
});
Thread.Sleep(300);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ContinueWith end");
});
//启动父任务
parentTask.Start();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " parentTask Start");
//等待任务结束 Wait只能等待父线程结束,没办法等到父线程的ContinueWith结束
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " parentTask wait start");
parentTask.Wait();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " parentTask wait end");
Console.ReadLine();
}
}
}
代码11:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 动态并行
{
//动态并行(TaskCreationOptions.AttchedToParent),父任务等待所有子任务完成后整个任务才算完成
class Program
{
//遍历二叉树
static void Main(string[] args)
{
Node root = GetNode();
DisPlayTree(root);
Console.ReadLine();
}
static Node GetNode()
{
Node root = new Node
{
Left = new Node
{
Left = new Node
{
Text = "L-L"
},
Right = new Node
{
Text = "L-R"
},
Text = "L"
},
Right = new Node
{
Left = new Node
{
Text = "R-L"
},
Right = new Node
{
Text = "R-R"
},
Text = "R"
},
Text = "Root"
};
return root;
}
static void DisPlayTree(Node root)
{
var task = Task.Factory.StartNew(() => DisplayNode(root),CancellationToken.None,TaskCreationOptions.None,TaskScheduler.Default);
task.Wait();
}
static void DisplayNode(Node current)
{
if (current.Left != null)
{
Task.Factory.StartNew(() => DisplayNode(current.Left),CancellationToken.None,TaskCreationOptions.AttachedToParent,TaskScheduler.Default);
}
if (current.Right != null)
{
Task.Factory.StartNew(() => DisplayNode(current.Right),CancellationToken.None,TaskCreationOptions.AttachedToParent,TaskScheduler.Default);
}
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 当前节点的值为:" + current.Text + ",处理的ThreadId = " + Thread.CurrentThread.ManagedThreadId);
}
}
class Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public string Text { get; set; }
}
}
代码12:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 取消任务
{
class Program
{
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
var longTask = new Task(() => TaskMethod("Task 1",10,cts.Token),cts.Token);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + longTask.Status);
cts.Cancel();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " First task has been cancelled before execution");
cts = new CancellationTokenSource();
longTask = new Task(() => TaskMethod("Task 2",10,cts.Token),cts.Token);
longTask.Start();
for (int i = 0; i < 5; i++)
{
Thread.Sleep(500);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + longTask.Status);
}
cts.Cancel();
for (int i = 0; i < 5; i++)
{
Thread.Sleep(500);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + longTask.Status);
}
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " A task has been Completed with result : " + longTask.Result);
Console.ReadLine();
}
private static int TaskMethod(string name, int seconds, CancellationToken token)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + name + " is running on a thread id : " + Thread.CurrentThread.ManagedThreadId + ", Is ThreadPool : " + Thread.CurrentThread.IsThreadPoolThread);
for (int i = 0; i < seconds; i++)
{
Thread.Sleep(1000);
if (token.IsCancellationRequested)
{
return -1;
}
}
return 42 * seconds;
}
}
}
代码13:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 处理任务中的异常_单个任务
{
class Program
{
static void Main(string[] args)
{
try
{
Task task = Task.Run(() => TaskMethod("Task 1", 2));
int result = task.GetAwaiter().GetResult();
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Result : " + result);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task 1 Exception : " + ex.Message);
}
Console.WriteLine("=================================================");
Console.ReadLine();
}
static int TaskMethod(string name, int seconds)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + name + " is running on a threadID : " + Thread.CurrentThread.ManagedThreadId + ", Is ThreadPool : " + Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(seconds * 1000);
throw new Exception("Boom!");
return 42 * seconds;
}
}
}
代码14:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 处理任务中的异常_多个任务
{
class Program
{
static void Main(string[] args)
{
try
{
var t1 = new Task(() => TaskMethod("Task 1", 3));
var t2 = new Task(() => TaskMethod("Task 2", 2));
t1.Start();
t2.Start();
Task.WaitAll(t1, t2);
}
catch (AggregateException ex)//AggregateException表示应用程序执行过程中发生的一个或多个错误
{
//对此System.AggregateException所包含的每个System.Exception调用处理程序
ex.Handle((exception) =>
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " exception.Message = " + exception.Message);
return true;
});
}
Console.ReadLine();
}
static int TaskMethod(string name, int seconds)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + name + " is running on ThreadId : " + Thread.CurrentThread.ManagedThreadId + ",Is ThreadPool : " + Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(seconds * 1000);
throw new Exception(name + " Boom!");
return 42 * seconds;
}
}
}
代码15:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Task.FromResult的应用
{
class Program
{
static void Main(string[] args)
{
System.Threading.Tasks.Task task = GetValueFromCache("006");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " 主程序继续执行");
string result = task.Result;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " result = " + result);
Console.ReadLine();
}
static IDictionary cache = new Dictionary()
{
{ "001","A"},
{ "002","B"},
{ "003","C"},
{ "004","D"},
{ "005","E"},
{ "006","F"},
};
static Task GetValueFromCache(string key)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " GetValueFromCache开始执行");
string result = string.Empty;
Thread.Sleep(5000);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " GetValueFromCache继续执行");
if (cache.TryGetValue(key, out result))
{
return System.Threading.Tasks.Task.FromResult(result);
}
return System.Threading.Tasks.Task.FromResult("null");
}
}
}
代码16:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Factory.FromAsync_带回调
{
class Program
{
delegate string AsyncTask(string threadName);
//执行的流程是 Test -> Callback -> task.ContinueWith
static void Main(string[] args)
{
AsyncTask d = Test;
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Option 1");
Task task = Task.Factory.FromAsync(d.BeginInvoke("AsyncTaskThread",CallBack,"a delegate async call**************"),d.EndInvoke);
task.ContinueWith(t => Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " callback finished,result:" + t.Result));
while (!task.IsCompleted)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status);
Thread.Sleep(500);
}
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status);
Console.ReadLine();
}
static string Test(string threadName)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Starting . . .");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Is ThreadPool : " + Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(2000);
Thread.CurrentThread.Name = threadName;
return "Thread name : " + Thread.CurrentThread.Name;
}
static void CallBack(IAsyncResult ar)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Starting a callback . . .");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " State passed to a callback : " + ar.AsyncState);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Is ThreadPool : " + Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Thread Pool worker thread id : " + Thread.CurrentThread.ManagedThreadId);
}
}
}
代码17:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Factory.FromAsync_不带回调
{
class Program
{
delegate string AsyncTask(string threadName);
//执行流程是 Test -> task.ContinueWith
static void Main(string[] args)
{
AsyncTask d = Test;
Task task = Task.Factory.FromAsync(d.BeginInvoke,d.EndInvoke,"AsyncTaskThread","a delegate async call******************");
task.ContinueWith(t => Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Task is completed,now running a continuation,result:" + t.Result));
while (!task.IsCompleted)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status);
Thread.Sleep(500);
}
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + task.Status);
Console.ReadLine();
}
static string Test(string threadName)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Starting . . .");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Is ThreradPool : " + Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(2000);
Thread.CurrentThread.Name = threadName;
return "Thread name = " + Thread.CurrentThread.Name;
}
}
}
代码18:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 判断任务是否完成
{
//当Task处于RanToCompleted、Cancelled或者Faulted状态时,IsCompleted返回true。
//判断一个Task是否完成,最简单的方法是if(task.Status == TaskStatus.TanToCompletion)
class Program
{
static CancellationTokenSource cts = new CancellationTokenSource();
static void Main(string[] args)
{
Task task1 = new Task(() => TaskMethod1(),cts.Token);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " task1.Status = " + task1.Status + " IsCompleted = " + task1.IsCompleted);
//task1.Start();
cts.CancelAfter(3000);
while (true)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " task1.Status = " + task1.Status + " IsCompleted = " + task1.IsCompleted);
Thread.Sleep(1000);
if (cts.IsCancellationRequested)
{
Thread.Sleep(1000);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " task1.Status = " + task1.Status + " IsCompleted = " + task1.IsCompleted);
break;
}
}
Console.ReadLine();
}
static void TaskMethod1()
{
while (!cts.IsCancellationRequested)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " TaskMethod1 IsCancellationRequested = " + cts.IsCancellationRequested);
Thread.Sleep(500);
return;
}
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " TaskMethod1 IsCancellationRequested = " + cts.IsCancellationRequested);
}
}
}