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のキャンセル処理(その2)

Last updated at Posted at 2025-04-10

はじめに

この記事は下記記事の続きです
【Unity】UniTaskのキャンセル処理(その1)

Try-Catch-Finallyを使用する

前回の記事から少し変えたソース(下記)で同様の操作をします
主な変更はTry-Catch-Finallyで囲みログを追加Catch内のReturn値です

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)
	{
		try
		{
			var val = await this.Process1(cancelToken);
			Debug.Log("結果:" + val);
		}
		catch(OperationCanceledException e)
		{
			Debug.Log("MainProcess catch");
		}
		finally
		{
			Debug.Log("MainProcess finally");
		}
	}

	private async UniTask<int> Process1(CancellationToken cancelToken)
	{
		try
		{
			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;
		}
		catch (OperationCanceledException e)
		{
			Debug.Log("Process1 catch");
			return 99;
		}
		finally
		{
			Debug.Log("Process1 finally");
		}
	}
}

正解

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

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

まとめ

重要なのは2の操作時なので2を見てみます。
どうやらキャンセルは例外を出しているようです。
if (cancelToken.IsCancellationRequested)ではなくTry-Catchでキャンセルの監視をしたほうがよさそうです。
Try-Catchで囲み、キャンセル時にしたい処理はCatch内に書く、キャンセルしてもしなくても最後に行いたい処理はfinally内に書くのがよさそうですね。
 
でも気になる・・。
なんでMainProcess側のCatch内のログは出てないの?
呼び出したProcess1で例外出たんだよ?
続きは次の記事で。

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

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?