Method call and waiting for return value

How do I call a method that returns bool, but inside this method to determine the value of bool, it calls an asynchronous web service?

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 I need the GetABoolean method to wait for CallAnAsyncMethod to complete and return the value before returning the bool back to the calling method.

I am not sure how to do this.

+3
source share
5 answers

Most asynchronous methods return IAsyncResult.

If you do this, you can use IAsyncResult.AsyncWaitHandle to lock (IAsyncResult.AsyncWaitHandle.WaitOne) to lock until the operation completes.

t


bool aBool;

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

+9

, CallAnAsyncMethodCompleted , e.Result .

+4

-?

+3

, , , , ( OP ).

-? ? ?

, -? , URL- ?

. .


"silverlight", , Silverlight. , "" .

SilverLight , , . . , GetABoolean , .

+2

CallAnAsyncMethod , ( , , ), .

If you have no control over the architecture that forces you to do this code asynchronously, you will need to control the variable and the loop to wait for it to complete.

bool myBool;
bool retrievingMyBool;
RetrieveABoolean(5);    

public bool RetrieveABoolean(int id)
{
    client.CallAnAsyncMethod(id);  // value is returned in a completed event handler.  Need to somehow get that value into aBool.
    retrievingMyBool = true;
    while (retrievingMyBool)
    {
        Thread.Sleep(100);
    }
}

private void completedEventHandler([[parameters go here]])
{
    // code to handle parameters
    myBool = // whatever
    retrievingMyBool = false    
}

This is a terrible decision, and in the future you will encounter giant headaches, especially if you ever need code that should be thread safe, but it can work as a hack.

0
source

Source: https://habr.com/ru/post/1704611/


All Articles