在App_Launching中初始化的静态变量突然为null

时间:2015-06-23 14:49:44

标签: c# windows-phone-8 windows-phone

Windows Phone 8项目。我有一个包含对图像的引用的类。我在app类的Launching事件处理程序中初始化了所述引用:

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    TheClass.Load();
}

//Elsewhere...
class TheClass
{
    static private int[] s_Pixels = null;

    static public void Load()
    {
        BitmapImage bi = new BitmapImage(new Uri("/res/image.png", UriKind.Relative));
        bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
        bi.ImageOpened += OnImageLoaded;
        bi.ImageFailed += OnImageFailed;
    }

    private static void OnImageLoaded(object o, RoutedEventArgs a)
    {
        BitmapImage bi = o as BitmapImage;
        s_Pixels = new WriteableBitmap(bi).Pixels;
    }

    // And consumers call this one:
    static public WriteableBitmap GetImage()
    {
        if (s_Pixels == null)
            SendDebugReport();
    }
}

此代码适用于我。但是我收到了那些调试报告,表明s_Pixels为空。我无法重现它,但我的用户显然可以。有一条代码路径可以在没有事先调用GetImage()的情况下调用Load()

Load未被调用,而不是我调用LoadOnImageLoaded永远不会被调用。

s_Pixels没有其他任何分配。

我检查图像加载错误。有一个ImageFailed事件处理程序留下日志跟踪。它永远不会被调用,为什么会这样 - 有问题的图像在应用程序的资源中。

怎么可能呢?如果不调用启动,Windows Phone应用程序如何初始化和加载?

1 个答案:

答案 0 :(得分:2)

Application_Launching仅在您的应用程序重新启动时调用。如果您将其发送到后台,并且系统最终将其墓碑化,然后用户重新激活它,您的静态数据将会消失,但Launching被调用。相反,您将接到Application_Activated的电话。

因此,基本上,您需要在LaunchingActivated方法上运行所有静态初始化。

您最有可能通过强制使用Visual Studio对应用程序进行逻辑删除来重现用户看到的问题:在项目选项的“调试”选项卡上选中“调试时停用时的墓碑”,在调试器下运行应用程序,按应用程序运行时的Windows键,然后切换回应用程序。

相关问题