如何从在此 object 方法的代码中启动的 BackgroundWorker 正确更新 属性 或 object?
How to correctly update a property of an object from a BackgroundWorker launched in the code of a methode of this object?
如果标题清楚,现在不要。这是来自 class 负责管理长操作的一段代码:
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来启动一些任务,它通过报告进度等完成...
我面临的唯一问题是,我似乎无法将 "Running" 设置为 true。即使在调用 setter 之后,它仍然保持其旧值。
非常感谢任何有关其工作原理的帮助和解释!
您在 setter 中的值和字段错误。你需要这个:
public bool Running
{
get { lock (runningLock) { return mRunning; } }
set
{
lock (runningLock)
{
RunningChanged.Invoke(value);
mRunning = value; // <=== LOOK HERE
}
}
}
如果标题清楚,现在不要。这是来自 class 负责管理长操作的一段代码:
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来启动一些任务,它通过报告进度等完成...
我面临的唯一问题是,我似乎无法将 "Running" 设置为 true。即使在调用 setter 之后,它仍然保持其旧值。
非常感谢任何有关其工作原理的帮助和解释!
您在 setter 中的值和字段错误。你需要这个:
public bool Running
{
get { lock (runningLock) { return mRunning; } }
set
{
lock (runningLock)
{
RunningChanged.Invoke(value);
mRunning = value; // <=== LOOK HERE
}
}
}