gpt4 book ai didi

c# - 在方法执行代码时显示进度表的最佳方式?

转载 作者:行者123 更新时间:2023-11-30 13:47:42 25 4
gpt4 key购买 nike

我有一个 WinForm 加载方法需要很长时间来收集一些数据以显示给用户。

在执行此方法时,我会显示一个带有大字体和单词“Loading”的表单。

但是有时会出现此错误并且“正在加载”进度表不会关闭,然后最终我的整个应用程序将退出:

创建窗口句柄时出错。在 System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)

当我在 load 方法中执行代码时,有没有更好的方法来显示我的进度/加载表单?

这是我的代码:

//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)
{
}

最佳答案

A BackgroundWorker是在不锁定 UI 线程的情况下执行长时间运行操作的好方法。

使用以下代码启动一个 BackgroundWorker 并显示一个加载表单。

// Configure a BackgroundWorker to perform your long running operation.
BackgroundWorker bg = new BackgroundWorker()
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

// Start the worker.
bg.RunWorkerAsync();

// Display the loading form.
loadingForm = new loadingForm();
loadingForm.ShowDialog();

这将导致以下方法在后台线程上执行。请注意,您不能从此线程操作 UI。尝试这样做将导致异常。

private void bg_DoWork(object sender, DoWorkEventArgs e)
{
// Perform your long running operation here.
// If you need to pass results on to the next
// stage you can do so by assigning a value
// to e.Result.
}

当长时间运行的操作完成时,将在 UI 线程上调用此方法。您现在可以安全地更新任何 UI 控件。在您的示例中,您可能想要关闭加载表单。

private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Retrieve the result pass from bg_DoWork() if any.
// Note, you may need to cast it to the desired data type.
object result = e.Result;

// Close the loading form.
loadingForm.Close();

// Update any other UI controls that may need to be updated.
}

关于c# - 在方法执行代码时显示进度表的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com