UnauthorizedAccessException: Invalid cross-thread access in Silverlight application (XAML/C#)

后端 未结 3 1988
情书的邮戳
情书的邮戳 2020-12-18 22:55

Relatively new to C# and wanted to try playing around with some third party web service API\'s with it.

Here is the XAML code

    

        
3条回答
  •  眼角桃花
    2020-12-18 23:40

    Another way to do this is to use the this.Dispatcher.CheckAccess() function. It is the same as what you get in WPF but it doesn't show up in your intellisense so you may not have seen it. What you do is check if you have access to the UI thread, and if you don't you recursively call yourself back on the UI 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();
    
        Console.WriteLine("I am done here");
        ////TwitterPost.Text = "hello there";
        postMyMessage(TwitterPost.Text);
    }
    
    private void postMyMessage(string text)
    {
        if (this.Dispatcher.CheckAccess())
            TwitterPost.Text = text;
        else
            this.Dispatcher.BeginInvoke(new Action(postMyMessage), text);
    }
    

    This is just a very simple example and can get unmanageable once you have more than a few controls. For some WPF/Silverlight stuff i have used a generic function which also takes the UI control to be updated as well as the update itself, that way i don't have one of these functions for every control on the page that may need updating from the results of a background thread.

提交回复
热议问题