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

后端 未结 3 1986
情书的邮戳
情书的邮戳 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:52

    A useful way to get easy cross thread access with the CheckAccess call is to wrap up a utility method in a static class - e.g.

    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;
        }
    
        /// 
        ///   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.
        /// 
        public static void Invoke(Action action)
        {
            if (Dispatcher.CheckAccess())
                action.Invoke();
            else
                Dispatcher.BeginInvoke(action);
        }
    }
    

    then you can wrap any calls that update the UI where you may be on a background thread like so:

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

    This way you don't have to know whether you are on a background thread or not and it avoids the overhead of adding methods to every control to check this.

提交回复
热议问题