为什么我在异步方法中的 while 循环没有停止? [英] Why doesn't my while loop in an async method stop?

查看:46
本文介绍了为什么我在异步方法中的 while 循环没有停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序的 async 方法中有以下代码

I've got the following code in an async method in my app

b_saving = true;

while (b_saving == true)
{
     try
     {
          if (1 == 1)
                b_saving = false;

          // anything down here should not execute?               
          i_should_not_run();

     }
     catch{
     }
     finally{
     }
}

我对这段代码的期望是,一旦 b_saving 设置为 false,它就会停止.然而,当我运行它时,情况并非如此.断点显示即使 b_saving 为假,该方法仍会继续运行.

My expectation with this code is that it will stop as soon as b_saving is set to false. Yet when I run it, this is not the case. Breakpoints show the method continues on even when b_saving is false.

while 循环在 C# 中不能这样工作吗?

Do while loops not work this way in C#?

推荐答案

即使您将 b_saving 设置为 false,循环仍将继续,除非您输入 break 命令在那里,while 循环将继续执行直到其块结束,然后才重新评估条件,在这种情况下很可能避免循环的另一次迭代,除非您将 b_saving 设置回 true在您的 i_should_not_run 方法中.

the loop will continue even after you set the b_saving to false, unless you put a break command in there, the while loop will continue executing until the end of its block and only then re-evaluate the condition and in this case most likely avoid another iteration of the loop, unless you set back b_saving to true inside your i_should_not_run method.

PS你可以在while里写一个更简单的条件,不用放==...

PS you can write a simpler condition in the while, no need to put the ==...

  while (b_saving)

这篇关于为什么我在异步方法中的 while 循环没有停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆