表单已关闭时调用时出错

发布于 2024-09-29 06:39:11 字数 1526 浏览 0 评论 0原文

我试图在从 sql 服务器查询的网格上显示一些信息。数据收集可能需要大约 10 秒,所以我不想锁定 UI 线程。

我目前有这样的代码:

ThreadPool.QueueUserWorkItem(DataUpdateThread, new UpdateParams(year));  

private struct UpdateParams
{
    internal string year;

    internal UpdateParams(string year)
    {
        this.year = year;
    }
}

private void DataUpdateThread(object state)
{
    DataTable dTable = new DataTable();
    try
    {
        this.Invoke((MethodInvoker)delegate
        {
            //stop data editing on the grid
            //scrolling marquee for user
            marquee.Visible = true;
            marquee.Enabled = true;
            grdMain.Visible = false;
            grdMain.DataSource = null;
        });

            UpdateParams parameters = (UpdateParams)state;            
            dTable = GetData(parameters.year);
    }
    catch (Exception ex)
    {
        this.Invoke((MethodInvoker)delegate
        {
            //log error + end user message
        });
    }
    finally
    {
        this.Invoke((MethodInvoker)delegate
        {
            grdMain.DataSource = dTable;
            grdMainLevel1.RefreshData();
            marquee.Visible = false;
            marquee.Enabled = false;
            grdMain.Visible = true;
        });
   }
}

这在大多数情况下都有效,除了如果在更新完成之前关闭它所在的表单,它将崩溃并出现错误:

在创建窗口句柄之前,无法在控件上调用 Invoke 或 BeginInvoke。

我知道该错误是因为表单不再存在,因此当 finally 部分尝试在 UI 线程上调用该方法时,它无法调用。

有没有更好的方法来完成这一切?我想我可以处理调用错误,但它看起来很混乱,我想我可能错过了一种更简单的方法。

I am trying to display some information on a grid queried from a sql server. The data gathering can take about 10 seconds so I don't want to lock the UI thread.

I currently have code like:

ThreadPool.QueueUserWorkItem(DataUpdateThread, new UpdateParams(year));  

private struct UpdateParams
{
    internal string year;

    internal UpdateParams(string year)
    {
        this.year = year;
    }
}

private void DataUpdateThread(object state)
{
    DataTable dTable = new DataTable();
    try
    {
        this.Invoke((MethodInvoker)delegate
        {
            //stop data editing on the grid
            //scrolling marquee for user
            marquee.Visible = true;
            marquee.Enabled = true;
            grdMain.Visible = false;
            grdMain.DataSource = null;
        });

            UpdateParams parameters = (UpdateParams)state;            
            dTable = GetData(parameters.year);
    }
    catch (Exception ex)
    {
        this.Invoke((MethodInvoker)delegate
        {
            //log error + end user message
        });
    }
    finally
    {
        this.Invoke((MethodInvoker)delegate
        {
            grdMain.DataSource = dTable;
            grdMainLevel1.RefreshData();
            marquee.Visible = false;
            marquee.Enabled = false;
            grdMain.Visible = true;
        });
   }
}

This works most of the time apart from if the form it is on is closed before the update completes it will crash with the error:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

I understand the error will be because the form no longer exists so when the finally section tries to invoke the method on the UI thread it can't.

Is there a better way to do this whole thing? I guess I can handle the invoke errors but it looks messy and I think I have probably missed a simpler way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眉黛浅 2024-10-06 06:39:11

您可以检查表单是否已关闭,如果表单已关闭,则不执行调用。 if (this.IsHandleCreated) 应该可以工作。然而,这仍然会产生问题,因为表单可以在检查和调用 BeginInvoke 之间关闭。唯一的“完全证明”解决方案是将整个调用包含在 try/catch 中。

You can check whether the form has been closed and don't do the invoke if the form has been closed. if (this.IsHandleCreated) should work. This can however still give problems because the form can be closed between the check and the call to BeginInvoke. The only 'full-proof' solution is then to enclose the entire call in a try/catch.

罗罗贝儿 2024-10-06 06:39:11

尝试在 Invoke() 之前使用 InvokeRequired()

Try to use InvokeRequired() before Invoke()

骄傲 2024-10-06 06:39:11

Invoke 在后台使用特殊的 WinForms SynchronizationContext,您可以在应用中的任何位置使用 SynchronizationContext.Current 访问它。

在 Reflector 中进行一些修改后的更正:实际上 Invoke 采用的是通过 PostMessage 进行编组的直接方式,它是在后台使用 SynchronizationContext 的 BackgroundWorker。如果没有窗口句柄,Invoke 将抛出异常。

基本上,您需要在启动线程之前将其存储在变量中,例如,当您仍在 UI 线程中时,并使用上下文中的 PostSend 方法线程的代码。这样做可以在没有窗口句柄的情况下正确整理这些东西。

Invoke uses a special WinForms SynchronizationContext behind the scenes that you can access with SynchronizationContext.Current anywhere in your app.

CORRECTION after some poking in Reflector: actually Invoke goes the direct way of marshalling via PostMessage, it's the BackgroundWorker that makes use of SynchronizationContext behind the scenes. Invoke will throw if it does not have a window handle.

Basically you need to store it in a variable before you start the thread, e.g. while you're still in your UI thread, and use Post or Send method of the context in the thread's code. Doing so will marshal the stuff properly without window handles.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文