【发布时间】:2013-03-24 01:15:15
【问题描述】:
我有一个 WinForm 加载方法,它需要很长时间才能收集一些数据以显示给用户。
在执行此方法时,我会显示一个带有“Loading”字样的大字体表单。
但有时会出现此错误并且“正在加载”进度表没有关闭,然后最终我的整个应用程序将退出:
创建窗口句柄时出错。在 System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
当我在加载方法中执行代码时,有没有更好的方法来显示我的进度/加载表单?
这是我的代码:
//I launch a thread here so that way the Progress_form will display to the user
//while the Load method is still executing code. I can not use .ShowDialog here
//or it will block.
//Progress_form displays the "Loading" form
Thread t = new Thread(new ThreadStart(Progress_form));
t.SetApartmentState(System.Threading.ApartmentState.STA);
t.IsBackground = true;
t.Start();
//This is where all the code is that gets the data from the database. This could
//take upwards of 20+ seconds.
//Now I want to close the form because I am at the end of the Load Method
try
{
//abort the Progress_form thread (close the form)
t.Abort();
//t.Interrupt();
}
catch (Exception)
{
}
【问题讨论】:
-
也许这里有一些想法:stackoverflow.com/q/15566176/327083
-
你应该换一种方式。在后台线程中执行加载工作并使用主 UI 线程显示某种进度条。
-
@VaibhavDesai - 如果耗时的操作涉及加载密集的 UI 对象,有时这在负载处理程序中是不可能的。在这种情况下,它必须由 UI 线程完成,因为它最终必须拥有这些对象。这就是为什么有些应用程序使用闪屏的原因。
标签: c# multithreading