概要
using System;
using System.Threading;
using System.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 Task RunAsync( CancellationToken cancellationToken )
{
try
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register( () => tcs.TrySetCanceled() );
await tcs.Task;
Debug.Log( "呼ばれない" );
}
catch ( OperationCanceledException e )
{
Debug.Log( "呼ばれる" );
}
}
private void Update()
{
if ( Input.GetKeyDown( KeyCode.Space ) )
{
m_cancellationTokenSource.Cancel();
}
}
}
参考サイト様