UniTask/Assets/UniRx.Async/UniTaskScheduler.cs

94 lines
3.5 KiB
C#
Raw Normal View History

2019-05-19 23:14:47 +08:00
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Threading;
namespace UniRx.Async
{
// UniTask has no scheduler like TaskScheduler.
// Only handle unobserved exception.
public static class UniTaskScheduler
{
public static event Action<Exception> UnobservedTaskException;
/// <summary>
/// Propagate OperationCanceledException to UnobservedTaskException when true. Default is false.
/// </summary>
public static bool PropagateOperationCanceledException = false;
/// <summary>
2020-04-18 04:07:59 +08:00
/// Write log type when catch unobserved exception and not registered UnobservedTaskException. Default is Error.
2019-05-19 23:14:47 +08:00
/// </summary>
2020-04-18 04:07:59 +08:00
public static UnityEngine.LogType UnobservedExceptionWriteLogType = UnityEngine.LogType.Error;
2019-05-19 23:14:47 +08:00
/// <summary>
2020-04-18 04:07:59 +08:00
/// Dispatch exception event to Unity MainThread. Default is true.
2019-05-19 23:14:47 +08:00
/// </summary>
public static bool DispatchUnityMainThread = true;
// cache delegate.
static readonly SendOrPostCallback handleExceptionInvoke = InvokeUnobservedTaskException;
internal static void PublishUnobservedTaskException(Exception ex)
{
if (ex != null)
{
if (!PropagateOperationCanceledException && ex is OperationCanceledException)
{
return;
}
if (UnobservedTaskException != null)
{
2020-04-18 04:07:59 +08:00
if (!DispatchUnityMainThread || Thread.CurrentThread.ManagedThreadId == PlayerLoopHelper.MainThreadId)
2019-05-19 23:14:47 +08:00
{
// allows inlining call.
UnobservedTaskException.Invoke(ex);
}
else
{
// Post to MainThread.
PlayerLoopHelper.UnitySynchronizationContext.Post(handleExceptionInvoke, ex);
}
}
else
{
string msg = null;
if (UnobservedExceptionWriteLogType != UnityEngine.LogType.Exception)
{
msg = "UnobservedTaskException:" + ex.ToString();
}
switch (UnobservedExceptionWriteLogType)
{
case UnityEngine.LogType.Error:
UnityEngine.Debug.LogError(msg);
break;
case UnityEngine.LogType.Assert:
UnityEngine.Debug.LogAssertion(msg);
break;
case UnityEngine.LogType.Warning:
UnityEngine.Debug.LogWarning(msg);
break;
case UnityEngine.LogType.Log:
UnityEngine.Debug.Log(msg);
break;
case UnityEngine.LogType.Exception:
UnityEngine.Debug.LogException(ex);
break;
default:
break;
}
}
}
}
static void InvokeUnobservedTaskException(object state)
{
UnobservedTaskException((Exception)state);
}
}
}
#endif