コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】UniTaskCompletionSource と CancellationToken を組み合わせて使う方法

概要

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

public sealed class Example : MonoBehaviour
{
    private readonly CancellationTokenSource m_cancellationTokenSource = new();

    private async void Start()
    {
        await RunAsync( m_cancellationTokenSource.Token );
    }

    private static async UniTask RunAsync( CancellationToken cancellationToken )
    {
        try
        {
            var tcs = new UniTaskCompletionSource();
            await tcs.Task.AttachExternalCancellation( cancellationToken );
            Debug.Log( "呼ばれない" );
        }
        catch ( OperationCanceledException e )
        {
            Debug.Log( "呼ばれる" );
        }
    }

    private void Update()
    {
        if ( Input.GetKeyDown( KeyCode.Space ) )
        {
            m_cancellationTokenSource.Cancel();
        }
    }
}