官网:使用 IAsyncResult 调用异步方法 - .NET | Microsoft Learn
private void button2_Click(object sender, EventArgs e)
testAction.myAction += (x, y) =>
{
Console.WriteLine(string.Format("Invoke-1 ThreadId:{0} {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString()));
Thread.Sleep(5 * 1000);
return x + y;
};
testAction.ExeMethod();
Console.WriteLine(string.Format("Invoke-5 ThreadId:{0} {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString()));
}
}
public class TestAction
{
public Func<int,int,int>myAction;
public void ExeMethod()
{
Console.WriteLine(string.Format("Invoke-2 ThreadId:{0} {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString()));
var ret = myAction.BeginInvoke(1, 2, new AsyncCallback(callback),myAction);
Thread.Sleep(3 * 1000);
Console.WriteLine(string.Format("Invoke-4( ThreadId:{0} {1}-返回值{2}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString(), ret.ToString()));
}
private void callback(IAsyncResult result)
{
var handler = (Func<int, int, int>)result.AsyncState;
handler?.EndInvoke(result);
Console.WriteLine(string.Format("Invoke-3 ThreadId:{0} {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString()));
}
}
----------------------------------------------------------------
结果
Invoke-2 ThreadId:1 2024/8/29 13:33:20
Invoke-1 ThreadId:4 2024/8/29 13:33:20
Invoke-4( ThreadId:1 2024/8/29 13:33:23-返回值System.Runtime.Remoting.Messaging.AsyncResult
Invoke-5 ThreadId:1 2024/8/29 13:33:23
Invoke-3 ThreadId:4 2024/8/29 13:33:25