调用方法并等待返回值

Sco*_*ttG 4 c# silverlight wcf 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

}
Run Code Online (Sandbox Code Playgroud)

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

我不知道该怎么做.

Ree*_*sey 8

大多数异步方法返回IAsyncResult.

如果是,您可以使用IAsyncResult.AsyncWaitHandle阻止(IAsyncResult.AsyncWaitHandle.WaitOne)阻止,直到操作完成.

即:

bool aBool;

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