需要添加一个当前正在生产的程序,我不能真正做很多架构更改。
主线程(T1) - > GUI元素 其他线程(T2 ...) - >计算元素(和外部事件)。
在T2上运行了一个对象类Foo
。
Foos是根据各种外部活动创建的。
我需要将一个DataGrid添加到一个新表单中,该表单只显示不同Foo对象的属性。
Foo
实施INotifyPropertyChanged
winform GridForm
有一个BindingList<Foo> FooList
对象。 GridView的数据绑定到它。
当我在NotifyPropertyChanged
中拨打Foo
时,显然我正在进行x线程调用
那不起作用。
我不能从主线程中生成我的Foo
对象,也不能在Thread2上创建表单。
我在这里讨论如何调用主线程。
我有一个静态类Foo-Brain
,它具有对主窗体的引用(因此我可以获得GUI线程。)。问题是如何将这一切联系在一起。
有什么想法吗?
(我正在考虑复制Foo
个对象并在GUI线程上运行它们并让FooList
包含这些对象,但这似乎是hacky和低效的方法。
感谢。
PS。希望每个人都对桑迪没问题。
编辑:示例代码:
class Person : INotifyPropertyChanged // this is the object that will be updated from a
//different thread; It will have the reference to the main form (GUI)
{
public event PropertyChangedEventHandler PropertyChanged;
string comments;
private Form1 mainForm = null;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged == null) return;
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public Person(string comments, Form1 f)
{
this.mainForm = f;
this.comments = comments;
}
public string Comments
{
get { return comments; }
set
{ comments = value;
NotifyPropertyChanged("Comments");
}
}
}
GUI表格中的代码:
private void Form1_Load(object sender, EventArgs e)
{
gridControl.DataSource = gridDataList;
}
private void runmethread()
{
Thread t = new Thread(anotherthread);
t.Start();
}
private void anotherthread()
{
gridDataList[0].Comments = "NEW THREAD";
}
private void button1_Click(object sender, EventArgs e)
{
runmethread();
}
private void button2_Click(object sender, EventArgs e)
{
gridDataList[0].Comments = "OLD THREAD";
}
显然button1_click导致x线程问题(我想解决的问题)
答案 0 :(得分:1)
我认为这就是你要问的......
将Foo中的INotifyPropertyChanged实现更改为:
public class Foo: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
if (mainForm.InvokeRequired)
{
mainForm.Invoke((MethodInvoker) delegate
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
});
}
else
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
这将确保每当PropertyChanged事件发生时(以及在其运行的整个持续时间内),它将是T1将运行的唯一事物。 所以PropertyChanged可以从两个线程中提出没问题。
related article你可能会发现教育或混乱:)没有中间立场:))