TaskAsyncHelper 一般方法的异步实现
public static class TaskAsyncHelper
{
/// <summary>
/// 将一个方法action异步运行,在执行完毕时执行回调callback
/// </summary>
/// <param name="action">异步方法,该方法没有参数,返回类型必须是void</param>
/// <param name="callback">异步方法执行完毕时执行的回调方法,该方法没有参数,返回类型必须是void</param>
public static void AsyncRun(Action action, Action callback)
{
_ = RunAsync(action, callback);
}
/// <summary>
/// 将一个方法action异步运行,在执行完毕时执行回调callback
/// </summary>
/// <typeparam name="T">异步方法参数类型</typeparam>
/// <param name="action">异步方法,该方法有1个参数,返回类型必须是void</param>
/// <param name="callback">异步方法执行完毕时执行的回调方法,该方法没有参数,返回类型必须是void</param>
/// <param name="par1">异步方法参数</param>
public static void AsyncRun<T>(Action<T> action, Action callback, T par1)
{
_ = RunAsync(action, callback, par1);
}
/// <summary>
/// 将一个方法action异步运行,在执行完毕时执行回调callback
/// </summary>
/// <typeparam name="T1">异步方法参数类型</typeparam>
/// <typeparam name="T2">异步方法参数类型</typeparam>
/// <param name="action">异步方法,该方法有2个参数,返回类型必须是void</param>
/// <param name="callback">异步方法执行完毕时执行的回调方法,该方法没有参数,返回类型必须是void</param>
/// <param name="par1">异步方法参数</param>
/// <param name="par2">异步方法参数</param>
public static void AsyncRun<T1, T2>(Action<T1, T2> action, Action callback, T1 par1, T2 par2)
{
_ = RunAsync(action, callback, par1, par2);
}
/// <summary>
/// 将一个方法function异步运行,在执行完毕时执行回调callback
/// </summary>
/// <typeparam name="TResult">异步方法的返回类型</typeparam>
/// <param name="function">异步方法,该方法没有参数,返回类型必须是TResult</param>
/// <param name="callback">异步方法执行完毕时执行的回调方法,该方法参数为TResult,返回类型必须是void</param>
public static void AsyncRun<TResult>(Func<TResult> function, Action<TResult> callback)
{
_ = RunAsync(function, callback);
}
static async Task RunAsync(Action action, Action callback)
{
Func<Task> taskFunc = () =>
{
return Task.Run(() =>
{
action();
});
};
await taskFunc();
callback?.Invoke();
}
static async Task RunAsync<T>(Action<T> action, Action callback, T par1)
{
Func<T, Task> taskFunc = (t1) =>
{
return Task.Run(() =>
{
action(t1);
});
};
await taskFunc(par1);
callback?.Invoke();
}
static async Task RunAsync<T1, T2>(Action<T1, T2> action, Action callback, T1 par1, T2 par2)
{
Func<T1, T2, Task> taskFunc = (t1, t2) =>
{
return Task.Run(() =>
{
action(t1, t2);
});
};
await taskFunc(par1, par2);
callback?.Invoke();
}
static async Task RunAsync<TResult>(Func<TResult> function, Action<TResult> callback)
{
Func<Task<TResult>> taskFunc = () =>
{
return Task.Run(() =>
{
return function();
});
};
TResult rslt = await taskFunc();
callback?.Invoke(rslt);
}
}
测试效果
public void Test()
{
Action action = () =>
{
SomeMethod();
};
TaskAsyncHelper.AsyncRun(action, null);
}