Error message while running the application of Silverlight program

Asked By 10 points N/A Posted on -
qa-featured

Hello,

I have made a Silverlight program to get custom entity attribute from CRM.

While running the application, a message appeared stating the invalid cross access.

System.UnauthorizedAccessException Message: Invalid cross-thread
access.
Stack:   at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject.SetValueInternal
(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
at System.Windows.DependencyObject.SetValue(DependencyProperty
dp, Object value)
at System.Windows.Controls.DataGrid.set_ItemsSource(IEnumerable
value)
at Vehicle_Symbol.MainPage. <RetrieveSymbol>b_1
(DataServiceCollection ' 1 results)

Retrieve Symbol                 Delete

Can anybody analyze this for me? What’s wrong with my program?

What should I do?

Thanks.

SHARE
Answered By 0 points N/A #138466

Error message while running the application of Silverlight program

qa-featured

Hello Anna,

To be able to get easy cross thread access with the CheckAccess call, you will need to wrap up a utility method in a static class, for instance the following:

public static class UIThread
{
    private static readonly Dispatcher Dispatcher;

    static UIThread()
    {
        // Store a reference to the current Dispatcher once per application
        Dispatcher = Deployment.Current.Dispatcher;
    }

    /// <summary>
    ///   Invokes the given action on the UI thread - if the current thread is the 
UI thread this will just invoke the action directly on
    ///   the current thread so it can be safely called without the calling method 
being aware of which thread it is on.
    /// </summary>
    public static void Invoke(Action action)
    {
        if (Dispatcher.CheckAccess())
            action.Invoke();
        else
            Dispatcher.BeginInvoke(action);
    }
}

After that, you can go ahead and then wrap any calls that update the user interface where you may be on a background thread as done in the following thread:

private void twitterCallback(IAsyncResult result)   
{   
        HttpWebRequest request = (HttpWebRequest)result.AsyncState;   
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);   
        TextReader reader = new StreamReader(response.GetResponseStream());   
        string strResponse = reader.ReadToEnd();   

        UIThread.Invoke(() => TwitterPost.Text = "hello there");
}   

Once you do it that way, you will not need to know whether you are on a background thread or not and it prevents the overhead caused by adding methods to every control to check this.

Regards,

Carl

Login/Register to Answer

Related Questions