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?

【Unity】UniTaskのキャンセル処理(その1)

Last updated at Posted at 2025-04-10

はじめに

UniTaskのキャンセルって意識してますか。
とりあえず
1、CancellationTokenSourceを作成
2、CancellationTokenを引数で渡す
3,キャンセルしたくなったらCancellationTokenSourceのCancel関数を呼ぶ
程度のことしか知らない危険なプログラマの1人である私の備忘録。

IsCancellationRequestedを使用

以下のソースで次の操作をします

1、Aキーを押すだけ
2、Aキーを押した直後にZキーを押して5秒くらい待機
それぞれどのようなログが出るでしょうか?

test.cs
public class UniTaskTest1 : MonoBehaviour
{
	private CancellationTokenSource cancelTonkenSource = new CancellationTokenSource();

	private void Update()
	{
		if(Input.GetKeyDown(KeyCode.A))
		{
			this.cancelTonkenSource = new CancellationTokenSource();
			this.MainProcess(this.cancelTonkenSource.Token).Forget();
		}
		else if (Input.GetKeyDown(KeyCode.Z))
		{
			this.cancelTonkenSource?.Cancel();
		}
	}

	private async UniTask MainProcess(CancellationToken cancelToken)
	{
		var val = await this.Process1(cancelToken);
		Debug.Log("結果:" + val);
	}

	private async UniTask<int> Process1(CancellationToken cancelToken)
	{
		Debug.Log("開始");
		int result = -1;
		await UniTask.Delay(TimeSpan.FromSeconds(3f), cancellationToken: cancelToken);
		Debug.Log("待機終了");

		result = 1;
		if(cancelToken.IsCancellationRequested)
		{
			Debug.Log("キャンセル2");
			return result;
		}

		result = 2;
		return result;
	}
}

正解

1、Aキーを押すだけ
スクリーンショット.png

2、Aキーを押した直後にZキーを押して5秒くらい待機
スクリーンショット 2025-04-09 235759.png

まとめ

・すぐにZキーを押してキャンセルさせると開始のログしか吐かれません。
・その下のif(cancelToken.IsCancellationRequested)の処理はキャンセルされた時用の処理に見えますが呼ばれもしません。
・MainProcess関数内の結果ログも吐かれません。

なんで?
続きは次の記事

次の記事(続き)
【Unity】UniTaskのキャンセル処理(その2)

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?