2016-11-10 157 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