2016-11-10 153 views
1

所以我有一個閃屏,這將有一段時間密集的代碼,我不希望它在主線程中運行。我已經做了一些應該停止線程並關閉窗體的代碼,但它不起作用。歡迎任何幫助。啓動畫面線程

代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Drawing; 
using System.Linq; 
using System.Reflection; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Threading; 

namespace Cobalt 
{ 
    partial class Cobalt : Form 
    { 
     public static bool splashCont { get; set; } 

     public Cobalt() 
     { 
      this.Text = "Cobalt V1.0.0"; 
      this.Width = 400; 
      this.Height = 100; 
      this.BackgroundImage = Properties.Resources.cobaltlgo; 
      this.FormBorderStyle = FormBorderStyle.None; 
      this.TopMost = true; 
      this.StartPosition = FormStartPosition.CenterScreen; 

      Thread splash = new Thread(new ThreadStart(splashLoadAction)); 
      splash.Start(); 

      if (splashCont) 
      { 
       splash.Abort(); 

       this.Close(); 
      } 
     } 

     private void splashLoadAction() 
     { 
      Thread.Sleep(5000); 
      Cobalt.splashCont = true; 
     } 
    } 
} 

該計劃只是停留在這個畫面: Screen 編輯: 我能夠通過使用下面的代碼來解決這個問題:

Invoke((MethodInvoker)delegate { MyNextForm.Show(); }); 

它調用UI線程上的MyNextForm.Show()

+0

什麼是「不工作」是什麼意思? – Enigmativity

+1

另外,如果有的話你叫'Thread.Abort的()',那麼你正在做的事情**非常錯誤的**,除非你試圖強行關閉整個應用程序。 – Enigmativity

回答

-1

當您在線程有Thread.sleep代碼,主線程將繼續執行,所以代碼

if (splashCont) 
{ 
    splash.Abort(); 

    this.Close(); 
} 

將執行好之前,你可以設置splashCnt =真。

檢查,如果你真的需要睡覺的線程,如果需要的話則需要考慮解決辦法的吧。

如果你真的想要線程睡眠時間比你可以使主線程等待子線程完成

while (splash.IsAlive) 
{ 
    Thread.Sleep(1000); 
} 

if (splashCont) 
{ 
    splash.Abort(); 
    this.Close(); 
} 
+0

但是,然後主線程停止並且GUI不出現 – steve

+0

如果您不想將Thread.Sleep放入平均線程中,那麼您可能必須從正在從線程調用的方法中取出Thread.Sleep也。 – Mallappa

0

如果你想在工作中的閃屏形式正在做,你可以簡化這個很大。這假定您的五秒鐘睡眠模擬正在完成的啓動工作。這樣,啓動工作完成後,啓動表單就會自動關閉。

partial class Cobalt : Form 
{ 
    public Cobalt() 
    { 
     this.Text = "Cobalt V1.0.0"; 
     this.Width = 400; 
     this.Height = 100; 
     this.BackgroundImage = Properties.Resources.cobaltlgo; 
     this.FormBorderStyle = FormBorderStyle.None; 
     this.TopMost = true; 
     this.StartPosition = FormStartPosition.CenterScreen; 
     this.Show(); 
     splashLoadAction(); 
     this.Close(); 
    } 

    private void splashLoadAction() 
    { 
     Thread.Sleep(5000); 
    } 
} 
0

您應該在閃屏形式中放置一個計時器,並在一段時間後關閉計時器。您可能需要修改應用程序入口點,以便在啓動主應用程序表單之前顯示此表單。

那麼,在實際生活中的應用,它可能比這更復雜,如果你想例如保持飛濺顯示更長,如果應用程序沒有準備好,或者直到實際顯示的主要形式。

如果需要時間將主應用程序窗口顯示爲在啓動關閉和應用程序可見之間的幾秒鐘內沒有顯示窗口,則可能會使用戶認爲應用程序崩潰。 ..

使用定時器,空閒和知名度的事件,你可以做像你想一旦你明白一切是如何工作的,你想要的是什麼。

+0

好主意。我會考慮他們 – steve