/// <summary>
/// 定义与方法同签名的事件委托
/// </summary>
public delegate void AsyncEventHandler();
/// <summary>
/// 定义与方法同签名的回调方法委托
/// </summary>
/// <param name="ex">异常信息对象</param>
public delegate void AsyncCallbackHandler(Exception ex);
/// <summary>
/// 异步调用引擎类
/// </summary>
public class AsyncCallEngine
{
/// <summary>
/// 执行异步方法调用
/// </summary>
/// <param name="asyncMethod">异步执行的方法</param>
/// <param name="callbackMethod">异步执行的方法执行后回调的方法</param>
public static void Process(AsyncEventHandler asyncMethod, AsyncCallbackHandler callbackMethod)
{
try
{
//实例化委托并初赋值
AsyncEventHandler acd = new AsyncEventHandler(asyncMethod);
//实例化回调方法并订阅
AsyncCallback acb = new AsyncCallback((ar) =>
{
//从异步状态ar.AsyncState中,获取委托对象
acd = (AsyncEventHandler)ar.AsyncState;
Exception _ex = null;
try
{
//异步完成,执行回调方法
acd.EndInvoke(ar);
}
catch (Exception ex)
{
_ex = ex;
}
//调用回调函数
if (callbackMethod != null)
{
callbackMethod(_ex);
}
});
//异步开始
IAsyncResult iar = acd.BeginInvoke(acb, acd);
}
catch (Exception ex)
{
//调用回调函数
if (callbackMethod != null)
{
callbackMethod(ex);
}
}
}
/// <summary>
/// 执行异步方法调用
/// </summary>
/// <param name="asyncMethod">异步执行的方法</param>
public static void Process(AsyncEventHandler asyncMethod)
{
Process(asyncMethod, null);
}
}