c# - 调用方法并等待返回值

标签 c# wcf silverlight asynchronous

如何调用返回 bool 值的方法,但在该方法内部为了确定 bool 值,它异步调用了 Web 服务?

bool myBool = GetABoolean(5);    

public bool GetABoolean(int id)
{

  bool aBool;

  client.CallAnAsyncMethod(id);  // value is returned in a completed event handler.  Need to somehow get that value into aBool.

  return aBool;  // this needs to NOT execute until aBool has a value

}

所以我需要的是让 GetABoolean 方法等到 CallAnAsyncMethod 完成并返回一个值,然后再将 bool 返回给调用方法。

我不知道该怎么做。

最佳答案

大多数异步方法返回 IAsyncResult。

如果你这样做,你可以使用 IAsyncResult.AsyncWaitHandle 来阻止 (IAsyncResult.AsyncWaitHandle.WaitOne) 来阻止直到操作完成。

即:

bool aBool;<p></p>

<p>IAsyncResult res = client.CallAnAsyncMethod(id);
res.AsyncWaitHandle.WaitOne();
// Do something here that computes a valid value for aBool!
return aBool;
</p>

关于c# - 调用方法并等待返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636180/

相关文章:

c# - Silverlight - 无需任何回发即可动态创建控件

c# - 如何从 Silverlight 5 中的自定义目录执行外部程序

javascript - C# 中 ajax 函数不返回数据

c# - StorageAccountList 请求在本地有效,但在 dotnet 应用程序中部署时无效

c# - 如何处理 WCF 服务中的事务

wcf - Visual Studio 2012 错误 Reference.svcmap 抛出错误

silverlight - 用于自动化 SilverLight 应用程序的工具

c# - 通过 C# 应用程序与网络通信?

c# - 代码后面的属性更改后控制模板触发器无法正确触发 [WPF]

asp.net - 如何使用配置设置在服务器启动时自动启动 WCF Windows 服务