pratpor
pratpor

Reputation: 2104

Invalid cross thread access

I am having this Model class where I am using DataContract to deserialize data received from server. So it has these two fields Data and DataColor where Data is being sent from server and DataColor is derived from it using some logic.

ModelClass.cs

    private double _data;
    [DataMember(Name = "data")]
    public double Data
    {
        get { return this._data; }
        set
        {
            SetField(ref _data, value, "Data");
            this.DataColor = Util1.GetColorFromData(value);
        }
    }

    private SolidColorBrush _dataColor;
    public SolidColorBrush DataColor
    {
        get { return this._dataColor; }
        set { SetField(ref _dataColor, value, "DataColor"); }
    }

To set DataColor I am calling one of my Util1 class function.

Util1.cs

    public static SolidColorBrush GetColorFromData(double data)
    {
        // apply some logic to get hexColor from data
        return Util2.GetSolidColorFromHex(string hexColor);
    }

which in turn calls another class' Util2 function to convert hexColor to SolidColorBrush

Util2.cs

    GetSolidColorFromHex(string hexColor)
    {
        return new SolidColorBrush(
            Color.FromArgb(
                255,
                Convert.ToByte(hexaColor.Substring(1, 2), 16),
                Convert.ToByte(hexaColor.Substring(3, 2), 16),
                Convert.ToByte(hexaColor.Substring(5, 2), 16)
            ));
    }

Now i don't have even the slightest idea why am I getting this Invalid cross thread access error in Util2.cs when I am trying to create SolidColorBrush object. I am not trying to change any UI object here.

I thought of using Deployment.Current.Dispatcher.BeginInvoke() here, but since I am returning values from function here, can't use Dispatcher I think.

I need to know why am I getting this error and how can I fix this?

I have wasted a lot of time on this and have tried to move GetSolidColorFromHex from Util2 to Util1. Still no success.

Also isn't there some general way to avoid Invalid cross thread by passing some context or something else maybe.

Thanks

Upvotes: 1

Views: 255

Answers (1)

Joe
Joe

Reputation: 1214

Although you're not trying to alter UI properties, a SolidColorBrush can only be instantiated on the UI thread.

You could do the creation on the UI thread to create a private variable of the brush, then return it.

Edit:

Without being at a PC to confirm, I believe something like this would work:

GetSolidColorFromHex(string hexColor)
{
    SolidColorBrush brush;
    Deployment.Current.Dispatcher.BeginInvoke(
        () => brush = new SolidColorBrush(
            Color.FromArgb(
                255,
                Convert.ToByte(hexaColor.Substring(1, 2), 16),
                Convert.ToByte(hexaColor.Substring(3, 2), 16),
                Convert.ToByte(hexaColor.Substring(5, 2), 16)
        )));

    return brush;
}

Upvotes: 1

Related Questions