Skip to content

Instantly share code, notes, and snippets.

@daviddebnar
Created April 13, 2023 11:54
Show Gist options
  • Save daviddebnar/4a2ecd68ed124731002a68668f9e8b32 to your computer and use it in GitHub Desktop.
Save daviddebnar/4a2ecd68ed124731002a68668f9e8b32 to your computer and use it in GitHub Desktop.

Concat Task Log Test

using System;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Text;
using Cysharp.Threading.Tasks;
using UnityEngine;
using StringBuilder = Cysharp.Text.Utf16ValueStringBuilder;
public class CancelledTaskLogTest : MonoBehaviour
{
private void Start()
{
var ct = this.GetCancellationTokenOnDestroy();
_ = ConcatThisTest(ct);
_ = ConcatThisCatchTest(ct);
_ = ConcatGameObjectCatchTest(ct);
_ = ConcatWrongCatchTest(ct);
_ = ConcatCorrectCatchTest(ct);
}
private async UniTaskVoid ConcatThisTest(CancellationToken ct)
{
await UniTask.Delay(TimeSpan.FromSeconds(10), cancellationToken: ct); // stop silently
var sb = ZString.CreateStringBuilder(); // never reached silently
sb.AppendFormat("[ConcatThisTest] I got destroyed {0}", this);
Debug.Log(sb.ToString());
}
private async UniTaskVoid ConcatThisCatchTest(CancellationToken ct)
{
try
{
await UniTask.Delay(TimeSpan.FromSeconds(10), cancellationToken: ct);
}
catch (OperationCanceledException e)
{
var sb = ZString.CreateStringBuilder();
sb.AppendFormat("[ConcatThisCatchTest] I got destroyed {0}", this); // prints "I got destroyed null"
Debug.Log(sb.ToString());
}
}
private async UniTaskVoid ConcatGameObjectCatchTest(CancellationToken ct)
{
try
{
await UniTask.Delay(TimeSpan.FromSeconds(10), cancellationToken: ct);
}
catch (OperationCanceledException)
{
var sb = ZString.CreateStringBuilder();
sb.AppendFormat("[ConcatGameObjectCatchTest] I got destroyed {0}", gameObject); // throws
Debug.Log(sb.ToString()); // never reached
}
}
private async UniTaskVoid ConcatWrongCatchTest(CancellationToken ct)
{
try
{
await UniTask.Delay(TimeSpan.FromSeconds(10), cancellationToken: ct);
}
catch (TaskCanceledException e)
{
Debug.LogException(e); // // never reached, since TaskCanceledException isn't the right type here
}
}
private async UniTaskVoid ConcatCorrectCatchTest(CancellationToken ct)
{
try
{
await UniTask.Delay(TimeSpan.FromSeconds(10), cancellationToken: ct);
}
catch (OperationCanceledException e)
{
Debug.LogException(e); // logs "The operation was canceled"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment