零、基本使用
using System.Threading.Tasks;
class Program
{
static void Main()
{
Console.WriteLine("Begain Task");
//启动一个Task
Task task = Task.Run(() =>
{
Console.WriteLine("Task");
});
Console.WriteLine("EndTask");
//等待Task完成
task.Wait();
}
}
一、启动Task
1、创建Task对象,Start启动Task
Task task = new Task(() =>
{
Console.WriteLine("Task");
});
task.Start();
2、Task.Run()创建启动Task
Task task = Task.Run(() =>
{
Console.WriteLine("Task");
});
3、TaskFactory启动任务,与Task.Run()本质相同
Task task = Task.Factory.StartNew(() =>
{
Console.WriteLine("Task");
});
二、停止Task
使用CancellationTokenSource对象和CancellationToken来作为标记关闭Task
using System.Net;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Func<CancellationToken, Task> canceledTask = async (token) =>
{
while (true)
{
if (token.IsCancellationRequested)
{
break;
}
Console.WriteLine("Hi");
await Task.Delay(1000);
}
Console.WriteLine("Task Cancel");
};
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
Task task = canceledTask(cancellationToken);
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
}
}
三、Task的延续
留言