Skip to content

Instantly share code, notes, and snippets.

@baobao
Last active October 20, 2019 14:53
Show Gist options
  • Select an option

  • Save baobao/722d9569c6365e4a3ca5952d94bc1c9c to your computer and use it in GitHub Desktop.

Select an option

Save baobao/722d9569c6365e4a3ca5952d94bc1c9c to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class TaskDelayCacncel : MonoBehaviour
{
// タスクをキャンセルさせるためのCancellationTokenSource
private CancellationTokenSource _cts;
public void OnClick()
{
// ボタンクリックしたらTaskのキャンセル
_cts.Cancel(true);
}
async void Start()
{
_cts = new CancellationTokenSource();
try
{
// 引数にトークンを渡す
await ExecuteWait(_cts.Token);
}
catch (OperationCanceledException e)
{
Debug.Log("タスクはキャンセルされた");
}
Debug.Log("Complete");
_cts = null;
}
async Task ExecuteWait(CancellationToken ct)
{
// Delayメソッドにトークンを渡す
await Task.Delay(5000, ct);
Debug.Log("Complete ExecuteWait");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment