Skip to content

Instantly share code, notes, and snippets.

@inoook
Created December 21, 2023 10:33
Show Gist options
  • Save inoook/2c473fd7245a0407fc85ed8fc1a0609d to your computer and use it in GitHub Desktop.
Save inoook/2c473fd7245a0407fc85ed8fc1a0609d to your computer and use it in GitHub Desktop.
AsyncEvent_Sample.cs
/**
CancellationTokenSource eventActCts;
void Cancel_AsynEventTest()
{
if(eventActCts != null)
{
eventActCts.Cancel();
}
eventActCts = null;
}
async Task AsyncEventTest()
{
try
{
eventActCts = new CancellationTokenSource();
float v = await asyncEvent_Test.AsyncEventAct(eventActCts.Token);
Debug.LogWarning("Result");
Debug.LogWarning(v);
}
catch (OperationCanceledException ex)
{
Debug.LogWarning($"OperationCanceledException: {ex}");
}
}
**/
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class AsyncEvent_Sample : MonoBehaviour
{
public delegate void TestHandler(float v);
public event TestHandler eventOnComplete;
float time = 0;
// Update is called once per frame
void Update()
{
if (isStart)
{
time += Time.deltaTime;
Debug.Log(time);
if(time > 2)
{
Debug.Log("END");
eventOnComplete?.Invoke(20);
isStart = false;
}
}
}
[SerializeField] bool isStart = false;
public async Task<float> AsyncEventAct(CancellationToken cancellationToken = default)
{
Debug.Log("AsyncEventAct");
isStart = true;
time = 0;
// -----
var tcs = new TaskCompletionSource<float>();
// https://gist.github.com/inoook/0c99004800273ef5e857b7ecf7117ae7
TestHandler handler = null;
handler = (float v) =>
{
// イベントのクリア 初期状態へ
eventOnComplete -= handler;
handler = null;
// 返り値のセット
tcs.TrySetResult(v);
};
eventOnComplete += handler;
using (cancellationToken.Register(() => {
// イベントのクリア 初期状態へ
eventOnComplete -= handler;
handler = null;
//
isStart = false;
//tcs.TrySetResult(-1);// キャンセルされても戻り値を返す場合
tcs.TrySetCanceled();// キャンセル OperationCanceledException を発生させる場合
}))
{
return await tcs.Task;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment