0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

UniTaskのTaskをキャンセル

Last updated at Posted at 2022-05-27

UniTaskでTaskをキャンセルする

using UnityEngine;
using System.Threading;
using Cysharp.Threading.Tasks;

class Hoge{
private CancellationTokenSource _cts;
private CancellationToken _ct;
private int num = 0;

async void Start(){
//CancellationTokenSourceのインスタンスを生成
_cts = new CancellationTokenSource();
//_ctsのTokenを生成
_ct = _cts.Token;
//引数でTokenを渡す
num = await GetInt(_ct);
Debug.Log(num);
}

private async UniTask<int> GetInt(CancellationToken cancellationToken = default)
{
    //他のメソッドの処理を待つ
    await UniTask.WaitWhile(() =>
    {
        //キャンセルの処理
        cancellationToken.ThrowIfCancellationRequested();
        //ReturnBoolInMethodからTrueが返ってきている間はWhileを実行する
        return ReturnBoolInMethod();
    });
    return 1;
}

private void Cancel(){
//Cancelのメソッドを実行すると今実行しているタスクをキャンセルできる
_cts.Cancel();

//キャンセルTokenを再生成することで複数回キャンセルすることができる
_cts = new CancellationTokenSource();
_ct = _cts.Token;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?