使用BeginInvoke方法来启动异步委托,使用第一个参数向异步委托传递一个回调委托。该回调委托将在异步委托完成处理时在方法被调用的线程上调用DelegateCallback方法。如果该线程当前正在执行其他代码,回调将等待至线程空闲为止。线程将继续存在,因为系统知道一个回调在挂起,所以不需要考虑回调准备好调用时线程不存在的情况。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
public delegate int AsyncInvoke(); //定义AsyncInvoke委托
public class TestAsyncInvoke
{
/// <summary>
/// 定义委托调用的静态方法
/// </summary>
/// <returns></returns>
public static int Method1()
{
Console.WriteLine($"Invoke Method1 on thread {Thread.CurrentThread.ManagedThreadId}");
return (1);
}
}
public class AsyncAction
{
public void CallbackAsyncDelegate()
{
AsyncCallback callBack = DelegateCallback;
AsyncInvoke method1 = TestAsyncInvoke.Method1;
Console.WriteLine($"Calling BeginInvoke on thread{Thread.CurrentThread.ManagedThreadId}");
IAsyncResult asyncResult = method1.BeginInvoke(callBack, method1);
return;
}
private static void DelegateCallback(IAsyncResult iresult)
{
Console.WriteLine($"Getting callback on thread{Thread.CurrentThread.ManagedThreadId}");
AsyncResult asyncResult = (AsyncResult)iresult;
AsyncInvoke method1 = (AsyncInvoke)asyncResult.AsyncDelegate;
int retVal = method1.EndInvoke(asyncResult);
Console.WriteLine($"ret (callback):{retVal}");
}
}
//获得一个匿名委托的完成通知
static void Main(string[] args)
{
AsyncAction t = new AsyncAction();
t.CallbackAsyncDelegate();
Console.ReadLine();
}
}
}
上述代码的输出如下。