一、场景1
1、可重复执行的耗时方法
二、代码示例1
Task _task = null;
CancellationTokenSource _cts = null;
private void Refresh()
{
if(this._task != null && !this._task.IsCompleted)
this._cts.Cancel();
//
this._cts = new CancellationTokenSource();
this._task = Task.Run(() => {
if(this._cts.IsCancellationRequested)
return;
//do something
}, this._cts.Token);
}
场景2
1、生命周期结束取消未完成任务
代码示例2
//本地变量
Task _task = null;
CancellationTokenSource _cts = null;
//初始化时,开启倒计时任务
private void Init()
{
this._cts = new CancellationTokenSource();
this._task = Task.Run(() => {
if(this._cts.IsCancellationRequested)
return;
//do something
}, this._cts.Token)
}
//退出时,取消未完成任务
private void Exit()
{
if(this._task != null && !this._task.IsCompleted)
this._cts.Cancel();
}