启动屏幕线程

时间:2016-11-10 03:14:05

标签: c# winforms splash-screen

所以我有一个启动画面会有一些时间密集的代码,我不希望它在主线程中运行。我已经制作了一些应该停止线程并关闭表单的代码,但它不起作用。欢迎任何帮助。

代码:

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()

3 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

您应该在启动画面中放置一个计时器,并在时间结束后关闭它。您可能希望修改应用程序入口点,以便在启动主申请表之前显示此表单。

嗯,在现实生活中,如果你想要的话,可能会比这个更复杂。如果应用程序还没有准备好,或者直到实际显示主表单,请保持更长时间的显示。

如果需要花时间将主应用程序窗口显示为在启动关闭和应用程序可见之间的几秒钟内没有显示窗口可能会让您的用户认为应用程序已崩溃,那么这可能很有用。

使用计时器,空闲和可见性事件,一旦您了解了所有工作的原因,您就可以按照自己的意愿做任何事情。

答案 2 :(得分:-1)

由于线程中有thread.sleep,主线程将继续执行代码

if (splashCont)
{
    splash.Abort();

    this.Close();
}
在你设置splashCnt = true之前,

会很好地执行。

检查是否确实需要睡眠线程,如果需要,则需要考虑解决方法。

如果你真的希望线程休眠,那么你可以让主线程等待子线程完成

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

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