我使用WindowsFormsApplicationBase來顯示啓動畫面。現在,當創建主窗體併發生錯誤時,應顯示一個消息框通知用戶。但是,消息框顯示在啓動畫面下,因此不可見。我需要關閉啓動畫面,以便我可以與用戶進行交互。關閉另一個線程的啓動畫面?
下面的代碼將提供一個跨線程操作異常:
class SingleInstanceApplication : WindowsFormsApplicationBase
{
private static SingleInstanceApplication instance;
public static void CloseSplash()
{
if (instance.SplashScreen != null)
instance.SplashScreen.Close();
}
}
錯誤:
Cross-thread operation not valid: Control 'Splash' accessed from a thread
other than the thread it was created on.
這甚至可能嗎?
通用的方式做到這一點是使用SynchronizationContext.Current拿到UI線程的SynchronizationContext。然後將它傳遞給後臺或其他線程中的任何作品。然後他們可以通過它將代表發佈到UI線程。 – Will