我有一个应用程序,用户可以启动任务,繁重的任务。我希望在一个用户界面网格中管理这些任务的进度(每行都是一个任务,并有一个进度栏),用户可以通过单击一个按钮(使用主线程)显示这个网格。我遇到的问题是交叉线程操作。我知道原因:每当任务进度发生变化(使用thread1)时,算法都会尝试更新网格数据源(使用主线程)。但我不知道怎么解决。
我的网格的DataSource属性设置为BindingList<BackgroundOperation>。
我的任务(BackgroundOperation)的定义
public class BackgroundOperation
{
public int progression;
public int Progression
{
get { return progression;}
set
{
progression = value;
OnPropertyChanged("Progression");
}
}
public event EventHandler OnRun;
public event EventHandler<ProgressChangedEventArgs> OnProgressChanged;
public event PropertyChangedEventHandler PropertyChanged;
public void Run()
{
var task = new Task(() =>
{
if (OnRun != null)
OnRun(this, null);
});
task.Start();
}
public void ReportProgress(int progression)
{
Progression = progression;
if (OnProgressChanged != null)
OnProgressChanged(this, new ProgressChangedEventArgs { Progression = progression });
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}发布于 2013-05-15 09:55:18
您需要在UI线程上运行OnProgressChanged (应该将BTW称为ProgressChanged)。您可以这样做:在创建类时保存SynchronizationContext,然后在那里对委托进行Post():
public class BackgroundOperation
{
private readonly SynchronizationContext m_synchronizationContext;
public BackgroundOperation()
{
m_synchronizationContext = SynchronizationContext.Current;
}
…
public void ReportProgress(int progression)
{
Progression = progression;
var handler = OnProgressChanged;
if (handler != null)
m_synchronizationContext.Post(
_ => handler(
this,
new ProgressChangedEventArgs { Progression = progression }),
null);
}
}https://stackoverflow.com/questions/16561172
复制相似问题