Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method and waiting for a return value

How do I call a method that returns a bool, but inside that method in order to determine the value of the bool, it calls a web service asyncronously?

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

}

So what I need is for the GetABoolean method to wait until CallAnAsyncMethod has completed and returned a value before returning the bool back to the calling method.

I'm not sure how to do this.

like image 426
ScottG Avatar asked Dec 03 '22 16:12

ScottG


1 Answers

Most asyncronous methods return IAsyncResult.

If yours does, you can use the IAsyncResult.AsyncWaitHandle to block (IAsyncResult.AsyncWaitHandle.WaitOne) to block until the operation completes.

ie:

bool aBool;

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

like image 56
Reed Copsey Avatar answered Dec 17 '22 23:12

Reed Copsey