繁体   English   中英

C#从本机线程修改UI

[英]C# Modify UI from native thread

让包含文本框的表单和设置它的方法(以不安全的方式):

class Form
{
    void SetTextBoxContent( String txt )
    {
        this._tb_TextBox.SetText( txt );
    }
}

现在,如果我想使这个线程安全,我需要做以下事情:

class Form
{
    void SetTextBoxContent( String txt )
    {
        if( this._tb_TextBox.InvokeRequired )
            this._tb_TextBox.Invoke( new DelegateSetTextBoxContentUnsafe( SetTextBoxContentUnsafe );
        else
            this.DelagSetTextBoxContentUnsafe( txt );
    }

    delegate void DelegateSetTextBoxContentUnsafe( String txt );

    void SetTextBoxContentUnsafe( String txt )
    {
        this._tb_TextBox.SetText( txt );
    }
}

对 ? 现在,如果我想从本机线程调用SetTextBoxContent(),该怎么办? 据我所知,没有办法调用对象的方法,所以我会将指向静态函数的指针传递给本机代码。 此函数将引用Form对象并执行方法调用本身:

class Form
{
    static Form instance;

    Form() { Form.instance = this }

    static void CallSetTextBoxContent( String txt )
    {
        Form.instance.SetTextBoxContent( txt );
    }

    void SetTextBoxContent( String txt )
    {
        if( this._tb_TextBox.InvokeRequired )
            this._tb_TextBox.Invoke( new DelagSetTextBoxContentUnsafe( SetTextBoxContentUnsafe );
        else
            this.DelagSetTextBoxContentUnsafe( txt );
    }

    delegate void DelagSetTextBoxContentUnsafe( String txt );

    void SetTextBoxContentUnsafe( String txt )
    {
        this._tb_TextBox.SetText( txt );
    }
}

现在我可以将我的静态函数CallSetTextBoxContent()传递给本机代码吗? 我在某处读到了我需要为此创建一个委托。 这意味着我需要为CallSetTextBoxContent()创建第二种委托,并将此委托传递给本机代码? 2个委托类型和3个函数做一些简单的事情看起来有点乱。 这是正确的方法吗?

谢谢 :)

编辑:忘了提到我使用的是紧凑的框架2.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM