为更好的理解我在此写成了窗体;
1.Task 线程操作
Winfrom UI 设计
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Task_Cancellation
{
public partial class Form1 : Form
{
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private ManualResetEvent manualResetEvent = new ManualResetEvent(true);
public Form1()
{
InitializeComponent();
}
void APPlinetext(string log)
{
BeginInvoke(new Action(() => {
textBox1.AppendText(log);
}));
}
private void button1_Click(object sender, EventArgs e)
{
_cancellationTokenSource =new CancellationTokenSource();
manualResetEvent = new ManualResetEvent(true);
int i = 0;
Task.Run(() =>
{
while (!_cancellationTokenSource.Token.IsCancellationRequested)
{
manualResetEvent.WaitOne();
Thread.Sleep(300);
APPlinetext(string.Format("[线程:{0}]:第{1}次{2}", Environment.CurrentManagedThreadId, i++, Environment.NewLine));
}
},_cancellationTokenSource.Token);
}
private void button2_Click(object sender, EventArgs e)//暂停
{
manualResetEvent?.Reset();
}
private void button3_Click(object sender, EventArgs e)//继续
{
manualResetEvent?.Set();
}
private void button4_Click(object sender, EventArgs e)//停止
{
_cancellationTokenSource.Cancel();
}
}
}
2.Task异步带有返回值
//方法编程
public static async Task<int> Task1()
{
int op = 0;
Console.WriteLine("无await:"+Environment.CurrentManagedThreadId + ":" + DateTime.Now.ToString("mm:ss:ff"));
await Task.Run(() => {Thread.Sleep(1000); Console.WriteLine("第一个异步:"+Environment.CurrentManagedThreadId+":"+DateTime.Now.ToString("mm:ss:ff")); op++; });
await Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("第二个异步:" + Environment.CurrentManagedThreadId + ":" + DateTime.Now.ToString("mm:ss:ff")); op++; });
return op;
}
//调用方法
public static void Runtask()
{
var ti = Task1();//异步开始
Console.WriteLine("运行等待:" + Environment.CurrentManagedThreadId);
Thread.Sleep(7000);//主线程等待
Console.WriteLine("等待完毕:"+Environment.CurrentManagedThreadId);
//Task.Result 会在运行完返回结果 期间主线程可以处理其他事务 后续进行Task 返回值判断
Console.WriteLine("控制台打印:" + ti.Result + ":" + DateTime.Now.ToString("mm:ss:ff"));
Console.WriteLine("运行完毕");
Console.Read();
}