上一篇写Thread
这一篇写Task
优缺点 百度吧 反正看那个好用用那个
创建控制台程序
新建TaskDom类
还是看怎么创建 怎么使用 怎么带参 怎么返回值 这里都体现了
class TaskDom
{
int count = 0;
public void Start()
{
Task.Run(Task01);
Task.Run(Task02);
Task task03 = Task.Run(() => { count = Task03(200); });
}
private int Task03( int num)
{
int _count = 0;
for (int i = 0; i < num; i++)
{
_count++;
Console.WriteLine("Task03 :" + i);
}
return _count;
}
private void Task02()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Task02 :" + i);
}
}
private void Task01()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Task01 :" + i);
}
}
}
static void Main(string[] args)
{
TaskDom task = new TaskDom();
task.Start();
}
结果
2)控制线程等待
修改代码 会在task03停止的时候打印出总数
public void Start()
{
Task.Run(Task01);
Task.Run(Task02);
Task task03 = Task.Run(() => { count = Task03(200); });
task03.Wait();
Console.WriteLine("task03_count:" + count);
// Task.Run(Task04);
}
3)停止
使用到CancellationTokenSource
创建CancellationTokenSourceDom类
class CancellationTokenSourceDom
{
CancellationTokenSource ct = new CancellationTokenSource();
public CancellationTokenSourceDom()
{
Task.Run(task01, ct.Token);
}
public void Stop()
{
ct.Cancel();
}
/// <summary>
/// CancellationTokenSource 只能停止 不会继续
/// </summary>
private async void task01()
{
while (true)
{
if (ct.IsCancellationRequested==false)
{
Console.WriteLine("正在执行");
await Task.Delay(3000);
}
}
}
}
static void Main(string[] args)
{
CancellationTokenSourceDom ct = new CancellationTokenSourceDom();
Console.WriteLine("输入stop停止..");
while (true)
{
string read = Console.ReadLine();
if (read.Equals("stop"))
{
ct.Stop();
}
}
Console.ReadKey();
}
3)因为Task没有停止继续 就没有别的办法了么
有的 需要一个小技巧
展示
class CancellationTokenSourceDom
{
public CancellationTokenSourceDom()
{
Task.Run(task02);
task02Start();
}
bool IsRun = false;
/// <summary>
// / 开始
/// </summary>
public void task02Start()
{
IsRun = true;
}
// / <summary>
// / 停止
// / </summary>
public void task02Stop()
{
IsRun = false;
}
private async void task02()
{
while (true)
{
if (true)
{
if (IsRun)
{
Console.WriteLine("任务执行中。。");
}
else
{
}
}
await Task.Delay(3000);
}
}
}
static void Main(string[] args)
{
CancellationTokenSourceDom ct = new CancellationTokenSourceDom();
Console.WriteLine("输入 start开始;输入stop停止.. ");
while (true)
{
string read = Console.ReadLine();
if (read.Equals("start"))
{
ct.task02Start();
}
else if (read.Equals("stop"))
{
ct.task02Stop();
Console.WriteLine("任务执行暂停");
}
}
Console.ReadKey();
}
好 task 说完
下一篇会说LOCK