using System;
namespace XGame.Framework.Asyncs
{
///
/// 异步扩展方法类!
///
public static class AsyncEx
{
///
/// 将Async加入到AsyncGroup 方便写代码!放心使用不用担心空指针
///
///
///
///
public static T Join(this T async, IAsyncGroup group) where T : IAsync
{
if (async != null && group != null)
{
group.AddAsync(async);
}
return async;
}
///
/// 执行成功且没有发生任何异常
///
///
///
///
///
public static IAsync Then(this IAsync async, Action action)
{
if (action == null) return async;
if (async == null || async.IsCompleted)
{
action.Invoke(async);
return async;
}
async.On(a =>
{
if (a.Exception == null)
{
action.Invoke(async);
}
});
return async;
}
///
/// 异步过程中产生了所关注的异常
/// 如果关注所有异常TException 设置为 Exception
///
///
///
///
///
///
public static TAsync Catch(this TAsync async, Action action) where TAsync : IAsync where TException : Exception
{
if (async == null || action == null) return async;
async.On(a =>
{
TException exc = a.Exception as TException;
if (exc != null)
{
action.Invoke(exc);
}
});
return async;
}
public static void SaveInvoke(this OnAsyncCompleted onAsyncCompleted, IAsync aAsync)
{
try
{
onAsyncCompleted?.Invoke(aAsync);
}
catch (Exception ex)
{
Log.Exception($"【Async Exception】Method:{onAsyncCompleted?.Method.Name ?? "null"} Async:{aAsync?.ToString() ?? "null"}\n", ex);
}
}
public static void SaveInvoke(this IAsyncListener listener, IAsync aAsync)
{
try
{
listener?.OnAsyncCompleted(aAsync);
}
catch (Exception ex)
{
Log.Exception($"【Async Exception】Listener:{listener?.GetType().FullName ?? "null"} Async:{aAsync?.ToString() ?? "null"}\n ", ex);
}
}
}
}