Skip to content

Instantly share code, notes, and snippets.

@baobao
Last active October 20, 2019 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baobao/7273e2931603d931f2a051586a8b9215 to your computer and use it in GitHub Desktop.
Save baobao/7273e2931603d931f2a051586a8b9215 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class MyTaskCancel : MonoBehaviour
{
// タスクをキャンセルさせるためのCancellationTokenSource
private CancellationTokenSource _cts;
public void OnClick()
{
// ボタンクリックしたらTaskのキャンセル
_cts?.Cancel();
}
async void Start()
{
_cts = new CancellationTokenSource();
try
{
// 引数にトークンを渡す
await MyTask(_cts.Token);
}
catch (OperationCanceledException e)
{
Debug.Log("タスクはキャンセルされた");
}
Debug.Log("Complete");
_cts = null;
}
async Task MyTask(CancellationToken ct)
{
// すでにキャンセルされているかチェック
// キャンセルされていたら例外をスロー
ct.ThrowIfCancellationRequested();
// 時間のかかる処理
await Task.Delay(5000);
// すでにキャンセルされているかチェック
// キャンセルされていたら例外をスロー
ct.ThrowIfCancellationRequested();
// キャンセル実行済みなら、以下のログは出力されない
Debug.Log("Complete ExecuteTask");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment