简体   繁体   English

异步函数返回false,但应返回true

[英]Async function returns false but should return true

I have a problem with a function that returns: false. 我对返回的函数有疑问:false。

The problem is that the: return success runs Before the actual: sucess = true is hit since it is an Async function. 问题在于:返回成功运行在实际:成功= true之前,因为它是一个异步函数。

How can this function return true as it do succeed? 该函数成功执行后如何返回true?

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. 我们将为这种情况找到解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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