我有一个正在使用的 API,但它的文档有限。有人告诉我,它执行的一些方法是异步调用的。
如何获取这些异步调用的结果。请注意,我没有做任何特别的事情来调用它们,API 处理异步部分。但我似乎无法从这些电话中得到“答复”——我假设那是因为它们在另一个线程中。
更新 - 我在下面包含了一些代码。 API 使用事件过程进行回调,但它似乎从未触发。
public partial class Window1 : Window
{
ClientAppServer newServer= new ClientAppServer();
public Window1()
{
InitializeComponent();
newServer.ReceiveRequest += ReadServerReply;
}
private void ReadServerReply(RemoteRequest rr)
{
MessageBox.Show("reading server reply");
if ((rr.TransferObject) is Gateways)
{
MessageBox.Show("you have gateways!");
}
}
private void login()
{
newServer.RetrieveCollection(typeof(Gateways), true);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.login();
}
最佳答案
在 .NET 中可以通过多种方式异步进行操作。由于您没有发布任何细节,我将概述更常见的模式:
异步等待句柄
通常您会发现(尤其是在 .NET 框架类中)以 Begin
和 End
命名的方法对(例如 BeginReceive
和 EndReceive
)。
调用 begin 函数返回一个 AsyncWaitHandle
对象,它可以像普通的 WaitHandle
一样用于同步线程(通过调用 WaitOne
或传递它进入静态 WaitHandle.WaitAny
或 WaitHandle.WaitAll
函数,然后被传递到相应的“结束”函数以获得函数的返回值(或者,如果一个发生,抛出遇到的异常)。
如果您使用简单的 .NET 工具异步调用方法(为函数创建委托(delegate)并调用 BeginInvoke
和 EndInvoke
),那么这就是您的方法会需要用到。然而,大多数内置异步操作支持的 API 将为您处理实际的异步调用部分,为您留下正确命名的 BeginXXX
和 EndXXX
函数,而不是强制你自己创建一个委托(delegate)。
使用 WaitHandle
的示例:
IAsyncResult result = object.BeginOperation(args);
result.AsyncWaitHandle.WaitOne();
// that will cause the current thread to block until
// the operation completes. Obviously this isn't
// exactly how you'd ordinarily use an async method
// (since you're essentially forcing it to be
// synchronous this way)
returnValue = object.EndOperation(result);
异步方法通常与事件结合在一起,如下所示。
事件
有时,异步完成的方法调用会在其完成时引发一个事件。这有时也与 AsyncWaitHandle
方法结合使用,以传递进程已完成的通知。例如,MSMQ 库在队列对象上有一个 BeginReceive
和 EndReceieve
函数,还有一个 ReceieveCompleted
事件。当事件触发时,它表示可以调用 EndReceive
,将调用返回的 AsyncWaitHandle
对象传递给 BeginReceive
。获取收到的实际消息。
无论哪种方式,您都可以附加到该事件并像使用任何其他事件一样使用它。
使用 AsyncWaitHandle
和事件的示例:
(代码中的某处)
object.OperationComplete += object_OperationComplete;
(别处)
IAsyncResult result = object.BeginOperation(args);
// at this point, you can either wait for the event
// to fire, or use the WaitHandle approach as shown
// in the previous example
...
void objectOperationComplete(object sender, AsyncOperationEventArgs e)
{
returnValue = object.EndOperation(e.AsyncResult);
}
这些通常以多种方式工作...您可以自己保留从 Begin 操作返回的 IAsyncResult
,但大多数库都会传递该 IAsyncResult
对象作为其特定 EventArgs
类的属性。
返回值作为 EventArgs
类的属性也很常见。虽然可以使用此值,但如果 Begin 操作返回 IAsyncResult
,调用相应的 End 函数始终是个好主意,即使您需要的数据在事件参数
。 End 函数通常也是捕获异常的方式。
回调
回调(在 .NET 中)是提供给异步函数的委托(delegate)。回调不仅仅用于异步函数,但在这种情况下,它们通常是您在调用完成时将调用的函数时提供的委托(delegate)。
回调类似于事件(因为它们都是基于委托(delegate)的),尽管方法调用和提供的回调之间存在更多的一对一关联。
使用回调的示例:
object.BeginOperation(args, OperationComplete);
...
void OperationComplete(SomeObject results)
{
...
}
关于C# 获取异步调用的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2630834/