Windows窗体中的跨线程调用有什么问题? [英] What's wrong with my cross-thread call in Windows Forms?

查看:125
本文介绍了Windows窗体中的跨线程调用有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows Forms应用程序中遇到问题.

I encounter a problem with a Windows Forms application.

必须从另一个线程显示一个表单.因此,在表单类中,我有以下代码:

A form must be displayed from another thread. So in the form class, I have the following code:

private delegate void DisplayDialogCallback();

public void DisplayDialog()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new DisplayDialogCallback(DisplayDialog));
    }
    else
    {
        this.ShowDialog();
    }
}

现在,每次运行此命令时,都会在this.ShowDialog();行上抛出InvalidOperationException:

Now, every time I run this, an InvalidOperationException is thrown on the line this.ShowDialog();:

跨线程操作无效:控制'SampleForm'是从创建该线程的线程之外的线程访问的."

这段代码有什么问题?这是进行跨线程调用的有效方法吗? ShowDialog()有什么特别之处吗?

What's wrong with this piece of code? Isn't it a valid way to make cross-thread calls? Is there something special with ShowDialog()?

推荐答案

尝试以下方法:

private delegate void DisplayDialogCallback();

public void DisplayDialog()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new DisplayDialogCallback(DisplayDialog));
    }
    else
    {
        if (this.Handle != (IntPtr)0) // you can also use: this.IsHandleCreated
        {
            this.ShowDialog();

            if (this.CanFocus)
            {
                this.Focus();
            }
        }
        else
        {
            // Handle the error
        }
    }
}

请注意InvokeRequired返回

如果控件的Handle为true,则为true 在与线程不同的线程上创建 调用线程(表明您 必须通过以下方式调用控件 调用方法);否则为假.

true if the control's Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false.

,因此,如果尚未创建控件,则返回值为false

and therefore, if the control has not been created, the return value will be false!

这篇关于Windows窗体中的跨线程调用有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆