启动画面线程
本文关键字:线程 动画 启动 | 更新日期: 2023-09-27 18:17:08
所以我有一个闪屏,它将有一些时间密集的代码,我不希望它在主线程中运行。我已经做了一些代码,应该停止线程和关闭表单,但它不工作。欢迎任何帮助。
代码: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;
}
}
}
程序就停留在这个屏幕上:屏幕编辑:我能够通过使用以下代码来解决这个问题:
Invoke((MethodInvoker)delegate { MyNextForm.Show(); });
在UI线程上调用MyNextForm.Show()
如果您希望工作以启动屏幕的形式完成,您可以大大简化这一点。这假设你的五秒钟睡眠模拟了启动工作的完成。这样,当启动工作完成时,splash表单就会自动关闭。
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);
}
}
您应该在闪屏表单中放置一个计时器,并在时间过去后关闭它。您可能需要修改应用程序入口点,以便在启动主应用程序表单之前显示此表单。
好吧,在实际的应用程序中,它可能比这更复杂,例如,如果你想在应用程序还没有准备好或直到主表单真正显示时,让splash显示更长时间。
这可能是有用的,如果需要时间来显示主应用程序窗口,因为在闪屏关闭和应用程序可见之间的几秒钟内没有窗口显示,可能会让你的用户认为应用程序已经崩溃…
使用定时器,空闲和可见性事件,你可以做任何你想做的事情,就像你想一旦你了解一切是如何工作的。
当你有线程时。在线程休眠时,主线程将继续执行,因此代码
if (splashCont)
{
splash.Abort();
this.Close();
}
将在您设置splashCnt = true之前执行得很好。
检查你是否真的需要休眠线程,如果需要,那么需要考虑解决方法。
如果你真的想让线程休眠,你可以让主线程等待子线程完成
while (splash.IsAlive)
{
Thread.Sleep(1000);
}
if (splashCont)
{
splash.Abort();
this.Close();
}