加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 发布和调试之间的区别?

发布时间:2020-12-15 04:23:05 所属栏目:百科 来源:网络整理
导读:当我将Visual Studio 2010配置从Debug更改为Release时,我得到一个非常奇怪的行为: 我有一个BackgroundWorker:_bg,在DoWork中我有: iswaiting = true; _bg.ReportProgress(1,filePath); while (iswaiting) { ; } //My other part of code (EDIT: something
当我将Visual Studio 2010配置从Debug更改为Release时,我得到一个非常奇怪的行为:

我有一个BackgroundWorker:_bg,在DoWork中我有:

iswaiting = true;
                _bg.ReportProgress(1,filePath);
                while (iswaiting)
                {                        
                  ;
                }
                //My other part of code (EDIT: something do to with the `result` I get from the user.)

在ProgressChanged中我有一个MessageBox,在用户交互之后,iswaiting将被设置为false并且_bg DoWork程序将继续.

void _bg_ProgressChanged(object sender,ProgressChangedEventArgs e)
    {
        //my other part of code........
       result = Microsoft.Windows.Controls.MessageBox.Show("Question","Title",MessageBoxButton.YesNoCancel,MessageBoxImage.Warning);

       iswaiting=false; 
       log(iswaiting.toString());                  
    }

当我从Visual Studio运行它或构建在调试模式时,所有这些都能很好地工作,但是当我将它构建到Release时,我永远不会离开while(等待)循环,虽然我可以从日志中看到iswaiting已经设置回到假.

编辑:

更好的方式是非常欢迎!

解决方法

这可能是由于线程优化造成的.为了安全地“看到”在释放模式下等待的变化,您需要一个内存屏障.

“修复”这个的最简单方法是将等待标记为volatile

volatile bool iswaiting;

话虽如此,像这样“旋转”将完全消耗一个CPU核心.更好的方法是使用ManualResetEvent来表示您可以继续.

// Add:
private ManualResetEvent allowProgress = new ManualResetEvent(false);

然后,你不会使用等待,而是:

_bg.ReportProgress(1,filePath);
allowProgress.WaitOne(); // This will block until it's set

要允许此操作继续,请使用:

result = Microsoft.Windows.Controls.MessageBox.Show("Question",MessageBoxImage.Warning);

  allowProgress.Set();

这里的优点是,在您被阻止时不会消耗CPU,并且您不必担心自己的内存障碍.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读