【问题标题】:Universal App network connection status通用应用网络连接状态
【发布时间】:2015-11-04 03:57:43
【问题描述】:

我正在尝试在 win8 中构建一个通用应用程序,其中一个功能是显示连接状态。状态显示为一个按钮,如果处于活动状态,则变为“绿色”,如果不活动,则变为“红色”。

这是网络检测代码:

        public class InternetConnectionChangedEventArgs : EventArgs
{
    public InternetConnectionChangedEventArgs(bool isConnected)
    {
        this.isConnected = isConnected;
    }
    private bool isConnected;

    public bool IsConnected
    {
        get { return isConnected; }
    }
}

public static class Network
{
    public static event EventHandler<InternetConnectionChangedEventArgs> 
        InternetConnectionChanged;

    static Network()
    {
        NetworkInformation.NetworkStatusChanged += (s) =>
        {
            if (InternetConnectionChanged != null)
            {
                var arg = new InternetConnectionChangedEventArgs(IsConnected);
                InternetConnectionChanged(null, arg);
            }
        };
    }

    public static bool IsConnected
    {
        get
        {
            var profile = NetworkInformation.GetInternetConnectionProfile();
            var isConnected = (profile != null
                && profile.GetNetworkConnectivityLevel() == 
                NetworkConnectivityLevel.InternetAccess);
            return isConnected;
        }
    }
}

所以最后我调用了函数来设置按钮的颜色,但是系统抛出一个异常,指出“应用程序正在使用为不同线程编组的线程”

这是 Main() 构造函数中的代码。

拔掉网线后应用程序会抛出异常..

    Network.InternetConnectionChanged +=async(s,e)=>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    isInternetON=e.IsConnected;
                });

                SetConnectionStaus(isInternetON);


            };

我的猜测是我在更新按钮颜色的同时从另一个线程调用一个线程.....请帮助!!

【问题讨论】:

    标签: c# asp.net xaml asp.net-web-api win-universal-app


    【解决方案1】:

    您可以使用此 sn-p 来更新 UI 属性以防止非 UI 威胁:

    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
    //Do thing / change value here
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多