0

I want to merge two model objects such that fields not null in new object updates the field of old one. But I am getting Invalid cross thread access in doing so. This is what I am doing:

I have this BaseJson and User classes in Application.Models namespace:

BaseJson

[DataContract]
public class BaseJson
{
    public void MergeFrom(BaseJson baseJson)
    {
        if (baseJson != null)
        {
            try
            {
                // http://stackoverflow.com/questions/8702603/merging-two-objects-in-c-sharp
                //Type t = typeof();
                var Properties = baseJson.GetType().GetProperties();
                //var properties = t.GetProperties();//.Where(prop => prop.CanRead && prop.CanWrite);

                foreach (var Property in Properties)
                {
                    var value = Property.GetValue(baseJson, null);
                    if (value != null)
                        Property.SetValue(this, value, null);
                }
            }
            catch
            {
                throw new Exception("Error Merging.");
            }
        }
    }
}

User

public class User : BaseJson, INotifyPropertyChanged
{
    private string _uid;
    [DataMember(Name="uid")]
    public string Uid
    {
        get { return this._uid; }
        set { SetField(ref _uid, value, "Uid"); }
    }

    // Other similar properties

    private void SetField<T>(ref T field, T value, string memberName=null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            RaisePropertyChanged(memberName);
        }
        App.GetUserManager().SaveUserLocally(this);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            // gives invalid cross thread access error here
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

For two user objects u1 and u2, I am calling

u1.MergeFrom(u2)

from different class ViewModel.cs.

My problem is, sometimes it doesn't give any error but for others it gives Invalid cross thread access in RaisePropertyChanged method.

pratpor
  • 1,954
  • 1
  • 27
  • 46
  • You have to use the dispatcher to marshal the call to INPC onto the UI thread. Have a public Dispatcher property on the VM, bind it to the UI's Dispatcher, or set it in some manner. Use that dispatcher for raising the event. –  Sep 29 '14 at 17:24
  • @Will thanks. Can you please elaborate on this or point me to a relevant link for how to do this. – pratpor Sep 29 '14 at 21:22
  • The linked duplicate will tell you how. Look at the accepted answer. –  Sep 30 '14 at 12:54

0 Answers0