C# 如何从后台线程获取WinPhone 8的屏幕分辨率
我正在创建一个库。我们需要的一件事是手机屏幕的像素分辨率(宽高比) 我们成功地使用了这种方法C# 如何从后台线程获取WinPhone 8的屏幕分辨率,c#,.net,xaml,windows-phone-8,dispatcher,C#,.net,Xaml,Windows Phone 8,Dispatcher,我正在创建一个库。我们需要的一件事是手机屏幕的像素分辨率(宽高比) 我们成功地使用了这种方法 Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth; Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight; 但是我们不处理后台线程调用此方法的情况,因此我们将其更改为使用Dispa
Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth;
Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight;
但是我们不处理后台线程调用此方法的情况,因此我们将其更改为使用Dispatcher:
System.Windows.Application.Current.RootVisual.Dispatcher.BeginInvoke(() =>
{
Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth;
Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight;
});
然而,我们抛出了一个“无效的跨线程访问”异常,似乎只是为了利用BeginInvoke
我们如何在不引用当前呈现的XAML页面的情况下正确处理此问题?仅访问
应用程序。Current.RootVisual
会引发无效的跨线程访问异常,因此您无法以这种方式访问调度程序。相反,请使用System.Windows.Deployment.Current.Dispatcher
:
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Screen.Width = (int) System.Windows.Application.Current.Host.Content.ActualWidth;
Screen.Height = (int) System.Windows.Application.Current.Host.Content.ActualHeight;
});