上下文時:的NullReferenceException關閉螺紋形式
我創建了開始之前運行閃屏的Windows窗體應用程序。很快,這裏是包含了我Program.cs
:
public static Thread splashScreenThread = null;
public static FormSplashScreen formSplashScreen;
[STAThread]
static void Main(string[] args) {
// Show splash screen
splashScreenThread = new Thread(new ThreadStart(ShowSplashScreen));
splashScreenThread.IsBackground = true;
splashScreenThread.Start();
// Load some components in background
LoadComponentsInBackground()
// Hide the splash screen
if (splashScreenThread != null) {
formSplashScreen.Invoke(new MethodInvoker(delegate {
formSplashScreen.Close();
formSplashScreen.Dispose();
}));
splashScreenThread = null;
}
// Start now the application
Application.Run();
}
private static void ShowSplashScreen() {
formSplashScreen = new FormSplashScreen();
formSplashScreen.ShowDialog();
}
問題:
我的問題不會發生,每次我啓動應用程序,它似乎是隨機的,更經常發生在一些電腦和少別人......所以我有點糊塗了,況且我真的不明白它從何而來:
一個NullReferenceException
在formSplashScreen.Invoke(...Close...)
線升高,但formSplashScreen
正確初始化(我檢查調試時) 。
我不知道這是否是來自該線程或從另一點...
可能的解決辦法:
我也許可以環繞線的東西,如低於造成的問題,但它不僅會繞開這個問題,我寧願理解它並妥善解決它。
while (splashScreenThread != null) {
try {
formSplashScreen.Invoke(new MethodInvoker(delegate {
formSplashScreen.Close();
formSplashScreen.Dispose();
}));
splashScreenThread = null;
} catch (Exception e) {
}
}
聽起來像競賽條件..嘗試將此代碼移到「ShowSplashScreen」方法中。 –