c# - volatile 变量的值在多线程中不改变

标签 c# multithreading .net-4.0 backgroundworker volatile

我有一个在后台运行的 winform 应用程序,它有一个 BackgroundWorker,它有一个每小时执行一些东西的无限循环。我的 UI Form 类是这样的:

public partial class frmAutoScript : Form
{
    private volatile bool _isDownloading = false;
    private bool IsDownloading { get { return this._isDownloading; } set { this._isDownloading = value; } }

    public frmAutoScript()
    {
        InitializeComponent();
        this.RunAutoSynchronization();
    }

    private void RunAutoSynchronization()
    {
        bool isDownloading = this.IsDownloading;

        BackgroundWorker bgwDownloader = new BackgroundWorker();
        bgwDownloader.WorkerReportsProgress = true;
        bgwDownloader.ProgressChanged += (sndr, evnt) =>
        {
            if (evnt.ProgressPercentage == 2)
                isDownloading = this.IsDownloading;
            else
            {
                this.IsDownloading = evnt.ProgressPercentage == 1;
                isDownloading = this.IsDownloading;
            }
        };
        bgwDownloader.DoWork += (sndr, evnt) =>
            {
                while (true)
                {
                    if (DateTime.Now.Hour == 16 &&
                        DateTime.Now.Minute == 0)
                    {
                        try
                        {
                            bgwDownloader.ReportProgress(2);
                            if (!isDownloading)
                            {
                                bgwDownloader.ReportProgress(1);
                                new Downloader().Download();
                            }
                            bgwDownloader.ReportProgress(0);
                        }
                        catch { }
                    }

                    System.Threading.Thread.Sleep(60000);
                }
            };
        bgwDownloader.RunWorkerAsync();
    }
}

frmAutoScript 中,我还有一个名为 btnDownload 的按钮,单击该按钮时,它将下载并更改 volatile 的值变量 _isDownloading。按钮的事件是这样的:

private void btnDownload_Click(object sender, EventArgs e)
{
    if (IsDownloading)
        MessageBox.Show("A download is currently ongoing. Please wait for the download to finish.",
            "Force Download", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    else
    {
        this.IsDownloading = true;
        BackgroundWorker bgwDownloader = new BackgroundWorker();
        bgwDownloader.DoWork += (sndr, evnt) =>
        {
            try
            {
                new Downloader().Download();
            }
            catch(Exception ex)
            {
                MessageBox.Show("An error occur during download. Please contact your system administrator.\n Exception: " +
                    ex.GetType().ToString() + "\nError Message:\n" + ex.Message + " Stack Trace:\n" + ex.StackTrace, "Download Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        };
        bgwDownloader.RunWorkerCompleted += (sndr, evnt) =>
        {
            this.IsDownloading = false;
        };
        bgwDownloader.RunWorkerAsync();
    }
}

但是当我单击按钮 btnDownload 并且 _isDownloading 设置为 true 时,当系统时间达到 4 :00 PM,尽管 _isDownloading 设置为 true,但 new Downloader().Download(); 再次执行。为什么会这样?

我的代码在 C# 中,框架 4,项目在 winforms 中,在 Visual Studio 2010 Pro 中构建。

最佳答案

您的代码不是针对 volatile 字段进行测试 - 它是针对 isDownloading 进行测试,它看起来像“本地”,但是 (因为它被捕获)实际上是一个常规(非volatile)字段。所以:要么使用某种内存屏障,要么强制其成为 volatile 读取。或者更简单:完全摆脱isDownloading,并检查该属性。

顺便说一句,volatile 的缓存失效属性不是关键字的意图,而是一个结果。它会工作,但个人我建议编写代码以按意图而不是结果,也许使用简单的或类似 Interlocked 的内容。

关于c# - volatile 变量的值在多线程中不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10781772/

相关文章:

c# - LOAD DATA INFILE 有时找不到文件?

c# - Web Api 属性路由中的可选参数

multithreading - 提高简单 Spring Batch 作业性能的技巧

c# - 从 Windows Phone 8.1 中的任务调用主线程

.net - 清除 PIN 缓存智能卡

c# - 内存中集合的 Linq 性能

c# - 发布错误: Found multiple publish output files with the same relative path

c# - TFS 复制工作项链接

c - 只有一个线程执行该函数

c# - 这是代码契约(Contract)重写器中的错误吗?