INotifyPropertyChanged with threads
.net, c#, datagridview, thread-safety, winforms
Solution
By design, a control can only be updated by the thread it was created in. This is why you are getting exceptions.
Consider using a BackgroundWorker and only update the member after the long lasting operation has completed by subscribing an eventhandler to `RunWorkerCompleted`.
Problem
I have a ``` BindingList<T> ``` which is bound to a datagridview. One property in my class takes long to calculate, so I threaded the action. After the calculation I raise the OnPropertyChanged() event to notify the grid that the value is ready. At least, that's the theory. But since the OnPropertyChanged Method is called from a differend thread I get some weired exceptions in the OnRowPrePaint method of the grid. Can anybody tell me how I fore the OnPropertyChanged event to be excecuted in the main thread? I can not use Form.Invoke, since the class MyClass is not aware that it runs in a Winforms application. ``` public class MyClass : INotifyPropertyChanged { public int FastMember {get;set;} private int? slowMember; public SlowMember { get { if (slowMember.HasValue) return slowMember.Value; else { Thread t = new Thread(getSlowMember); t.Start(); return -1; } } } private void getSlowMember() { Thread.Sleep(1000); slowMember = 5; OnPropertyChanged("SlowMember"); } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChangingEventHandler eh = PropertyChanging; if (eh != null) { eh(this, e); } } } ```