简体   繁体   中英

Async function returns false but should return true

I have a problem with a function that returns: false.

The problem is that the: return success runs Before the actual: sucess = true is hit since it is an Async function.

How can this function return true as it do succeed?

public bool onefunction(ChromiumWebBrowser browser) {
  bool success = false;
  browser.GetMainFrame().EvaluateScriptAsync("someinfo").ContinueWith(t => {
    if (t.IsFaulted == false) {
      var response = t.Result;
      if (response.Success) {
        success = true;
      }
    }
  });

  //It returns false because this code runs before: "success = true"
  return success;
}

"Async all the way"-Approach:

public async Task<bool> onefunction(ChromiumWebBrowser browser) {
  bool success = false;
  try
  {
      var response = await browser.GetMainFrame().EvaluateScriptAsync("someinfo");
      succes = response.Success;
  }
  catch( Exception ex )
  {
      // TODO: Write Errorlog
  }

  return success;
}

Mind: This will mean that you need to change the calling code, too. If you cannot do that, please advise. We'll find a solution for that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM