You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

布尔类型函数内部变量值无法更改的技术问题

问题:异步回调中更新变量后,函数返回错误结果的解决办法

先看一下你的代码:

private bool GetSource(string toSearchFor) {
 bool test = false;
 func3("2000");
 browser.GetSourceAsync().ContinueWith(taskHtml => {
 var html = taskHtml.Result;
 //printLine(html.ToString());
 if(html.ToString().Contains(toSearchFor)) {
 test = true;
 printLine("found TOSEARCHFOR:" + toSearchFor + " and test variable is: " + test);
 } else {
 test = false;
 }
 });
 if(test == false) {
 printLine("false in test area-----------------------------");
 return false;
 } else {
 printLine("true i...

问题原因

兄弟,你这个问题是异步编程里非常典型的「主线程抢先执行」问题:browser.GetSourceAsync()是异步方法,它会在后台线程默默执行获取源码的操作,ContinueWith()里的回调要等异步操作完成才会触发。但你的主线程根本不会等这个异步任务结束,直接就往下跑了——也就是回调还没来得及把test改成true,主线程已经执行到if(test == false)的判断了,自然会返回错误结果。

解决方案:用async/await替代ContinueWith

现在C#处理异步操作最推荐的是async/await语法,它能让异步代码像同步代码一样直观,彻底避开回调时机的坑。修改后的代码如下:

// 注意:异步方法需要返回Task或Task<T>,所以把返回类型从bool改成Task<bool>
private async Task<bool> GetSource(string toSearchFor) {
    func3("2000");
    // await会暂停当前方法,等GetSourceAsync()完成后再继续执行
    var html = await browser.GetSourceAsync();
    //printLine(html.ToString());
    bool test = html.Contains(toSearchFor);
    if (test) {
        printLine($"found TOSEARCHFOR:{toSearchFor} and test variable is: {test}");
    }
    printLine(test ? "true in test area-----------------------------" : "false in test area-----------------------------");
    return test;
}

为什么这样改?

  • await关键字会帮你「等待」异步操作完成,确保你在判断网页内容之前,已经拿到了完整的源码,不会出现主线程抢先跑的情况。
  • 去掉了ContinueWith()的回调嵌套,代码逻辑更线性,可读性直接拉满,后续维护也更方便。

特殊情况:如果不能修改函数返回类型?

要是因为项目限制,必须让函数返回bool而不是Task<bool>,可以用阻塞方式(非常不推荐,会阻塞线程影响性能,还可能引发死锁):

private bool GetSource(string toSearchFor) {
    func3("2000");
    // 用.Result强制阻塞主线程,等待异步操作完成
    var html = browser.GetSourceAsync().Result;
    bool test = html.Contains(toSearchFor);
    if (test) {
        printLine($"found TOSEARCHFOR:{toSearchFor} and test variable is: {test}");
    }
    printLine(test ? "true in test area-----------------------------" : "false in test area-----------------------------");
    return test;
}

⚠️ 划重点:这种方式尽量别用,尤其是在UI线程里,很容易导致程序卡死,优先选async/await的方案。

内容的提问来源于stack exchange,提问作者wilky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:29:03