Last active
October 20, 2019 16:36
-
-
Save baobao/7273e2931603d931f2a051586a8b9215 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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