【发布时间】:2013-03-08 16:35:26
【问题描述】:
鉴于以下课程,在备用线程上启动启动屏幕:
public partial class SplashForm : Form
{
private static Thread _splashThread;
private static SplashForm _splashForm;
public SplashForm()
{
InitializeComponent();
}
// Show the Splash Screen (Loading...)
public static void ShowSplash()
{
if (_splashThread == null)
{
// Show the form in a new thread.
_splashThread = new Thread(new ThreadStart(DoShowSplash));
_splashThread.IsBackground = true;
_splashThread.Start();
}
}
// Called by the thread.
private static void DoShowSplash()
{
if (_splashForm == null)
_splashForm = new SplashForm();
// Create a new message pump on this thread (started from ShowSplash).
Application.Run(_splashForm);
}
// Close the splash (Loading...) screen.
public static void CloseSplash()
{
// Need to call on the thread that launched this splash.
if (_splashForm.InvokeRequired)
_splashForm.Invoke(new MethodInvoker(CloseSplash));
else
Application.ExitThread();
}
}
使用以下相应命令调用并关闭它
SplashForm.ShowSplash();
SplashForm.CloseSplash();
很好。
我对 TPL 并不完全陌生,当然我们可以使用以下简单的方法在另一个线程上显示表单:
Task task = Task.Factory.StartNew(() =>
{
SomeForm someForm = new SomeForm();
someForm.ShowDialog();
};
我的问题是在您准备好后关闭此SomeForm。肯定有比在SomeForm 类中创建public static 方法更好的方法,比如
private static SomeForm _someForm;
public static void CloseSomeForm()
{
if (_someForm.InvokeRequired)
_someForm.Invoke(new MethodInvoker(CloseSomeForm));
}
我的问题是,使用任务并行库 (TPL) 使用上面的 SplashForm 类执行相同操作的最佳方法是什么? 具体来说,关闭调用的表单的最佳方法是什么?在 UI 的另一个线程上。
【问题讨论】:
-
把闪屏放到另一个线程上的目的是什么?
-
保持活跃(显示动画等)。不阻塞用户界面。