INotifyPropertyChanged与线程 [英] INotifyPropertyChanged with threads

查看:250
本文介绍了INotifyPropertyChanged与线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

 BindingList<T>

它绑定到一个datagridview。我的课程中的一个属性需要很长的时间来计算,所以我采取了行动。在计算之后,我提高了OnPropertyChanged()事件以通知网格该值已准备就绪。

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.

至少这就是理论。但是,由于OnPropertyChanged方法是从一个不同的线程调用的,所以我在网格的OnRowPrePaint方法中得到一些例外。

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.

有人可以告诉我如何将OnPropertyChanged事件在主线程中被表示?我不能使用Form.Invoke,因为MyClass类不知道它在Winforms应用程序中运行。

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);
        }
   }

}


推荐答案

通过设计,一个控件只能被创建的线程更新,这就是为什么你会得到例外。

By design, a control can only be updated by the thread it was created in. This is why you are getting exceptions.

BackgroundWorker ,只能在长时间后更新成员通过将事件处理程序订阅到 RunWorkerCompleted 来完成持久操作。

Consider using a BackgroundWorker and only update the member after the long lasting operation has completed by subscribing an eventhandler to RunWorkerCompleted.

这篇关于INotifyPropertyChanged与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆