如何从以该对象的方法代码启动的BackgroundWorker中正确更新对象的属性?

时间:2018-07-19 14:19:04

标签: c# multithreading locking backgroundworker

如果标题清楚,则不要。这是负责管理长时间操作的一类代码:

public class LongProcess
{
    public delegate void RunningChangedEventHandler(bool running);

    public event RunningChangedEventHandler RunningChanged;

    private object runningLock = new object();
    public bool Running
    {
        get { lock (runningLock) { return mRunning; } }
        set
        {
            lock (runningLock)
            {
                RunningChanged.Invoke(value);
                value = mRunning;
            }
        }
    }

    public void start()
    {
        mWorker = new BackgroundWorker();
        mWorker.DoWork += Bg_DoWork;
        mWorker.RunWorkerAsync();
    }

    private void Bg_DoWork(object sender, DoWorkEventArgs e)
    {
        Running = true;
        // Some things to do here ... but I need Running to be equals to true and it is not
    }
}

在主程序中,我使用LongProcess来启动一些任务,它是通过报表进度等完成的...

我面临的唯一问题是,似乎无法将“运行”设置为true。即使在调用设置器之后,它仍然保持其旧值。

对于此方法的任何帮助和解释将不胜感激!

1 个答案:

答案 0 :(得分:3)

您拥有自己的价值,并在二传手中打错了方向。您需要这个:

public bool Running
{
    get { lock (runningLock) { return mRunning; } }
    set
    {
        lock (runningLock)
        {
            RunningChanged.Invoke(value);
            mRunning = value; // <=== LOOK HERE
        }
    }
}