BeginInvoke和EndInvoke的作用是把一个同步方法改成异步执行,改造过程主要有3步:
·增加一个与方法对应的委托;
·增加一个AsyncCallback委托类型的回调函数(在函数体调用EndInvoke获取返回值);
·将方法的参数、回调函数和委托变量传给BeginInvoke;
下面是一个简单的示例:
代码如下 |
复制代码 |
public class Test
{
///
/// 原始方法
///
///
private int Todo()
{
return 100;
}
///
/// 增加方法对应的委托
///
///
delegate int TodoHandler();
///
/// 增加AsyncCallback委托类型的回调函数
///
///
private void TodoCallback(IAsyncResult ar)
{
TodoHandler handler = (TodoHandler)ar.AsyncState;
Console.WriteLine(handler.EndInvoke(ar));
}
///
/// 调用示例
///
public void InvokeTest()
{
TodoHandler handler = new TodoHandler(Todo);
handler.BeginInvoke(TodoCallback, handler);
}
}
|
参考很多类异步方法命名方式BeginXXX和EndXXX,对上面类稍做修改:
代码如下 |
复制代码 |
public class Test
{
public int Todo(int a, int b)
{
return a + b;
}
private delegate int TodoHandler(int a, int b);
private TodoHandler _todo = null;
public Test()
{
_todo = Todo;
}
public IAsyncResult BeginTodo(int a, int b, AsyncCallback callback, object state)
{
return _todo.BeginInvoke(a, b, callback, state);
}
public int EndTodo(IAsyncResult ar)
{
return _todo.EndInvoke(ar);
}
}
public class Program
{
static void TodoCallback(IAsyncResult ar)
{
Test test = (Test)ar.AsyncState;
Console.WriteLine(test.EndTodo(ar));
}
static public void Main(string[] args)
{
Test test = new Test();
test.BeginTodo(2, 3, TodoCallback, test);
Console.ReadKey();
}
}
|
BeginTodo方法返回类型为IAsyncResult,网上看到有人这么调用:
代码如下 |
复制代码 |
static public void Main(string[] args)
{
Test test = new Test();
IAsyncResult result = test.BeginTodo(2, 3, null, null);
Console.WriteLine(test.EndTodo(result));
Console.ReadKey();
}
|