
这是XAML代码
<GrID x:name="ContentGrID" GrID.Row="1"> <StackPanel> <button Content="Load Data" Click="button_Click" /> <TextBlock x:name="TwitterPost" Text="Here I am"/> </StackPanel> </GrID>
这里是C#代码
private voID button_Click(object sender,RoutedEventArgs e) { httpWebRequest request = (httpWebRequest)WebRequest.Create("http://API.twitter.com/1/users/show/keykoo.xml"); request.Method = "GET"; request.BeginGetResponse(new AsyncCallback(twitterCallback),request); } 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"; } 我猜这是因为回调在一个单独的线程上执行的UI呢?在C#中处理这些类型的交互的正常流程是什么?
谢谢.
解决方法 通过CheckAccess调用获取简单的交叉线程访问的一个有用的方法是在静态类中包装一个实用程序方法.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); }} 那么您可以将任何更新UI的调用包装在背景线程上,如下所示:
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");} 这样你不必知道你是否处于后台线程,并且避免了向每个控件添加方法来检查这一点的开销.
总结以上是内存溢出为你收集整理的UnauthorizedAccessException:Silverlight应用程序(XAML / C#)中的跨线程访问无效全部内容,希望文章能够帮你解决UnauthorizedAccessException:Silverlight应用程序(XAML / C#)中的跨线程访问无效所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)