如何调用返回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;IAsyncResult res = client.CallAnAsyncMethod(id); res.AsyncWaitHandle.WaitOne(); // Do something here that computes a valid value for aBool! return aBool;