【问题标题】:C# Modify UI from native threadC# 从本机线程修改 UI
【发布时间】:2015-04-20 13:06:08
【问题描述】:

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

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

【问题讨论】:

  • 您不必创建自己的代表。使用现有的。 Action<string> 应该与你的方法的签名相匹配。
  • 谢谢。看起来更干净,但这可以传递给本机代码吗?
  • 它就像任何其他代表一样。您可以将其传递给本机代码,就像为其他委托所做的那样。

标签: c# multithreading user-interface delegates pinvoke


【解决方案1】:

【讨论】:

  • 谢谢。我可以使用从这个函数获得的IntPtr 作为本机代码中的常规函数​​指针吗?我忘了提到我正在使用标准的非托管 C++。
  • @Virus721 是的,你可以。
  • 问问自己以这种方式耦合 UI 和非托管代码是否明智。
  • 使用静态的东西似乎有点脏,但否则我看不出有什么问题。我没有提到它,但同样的非托管代码也用于 Android 和 JNI,所以我还有其他一些限制。
猜你喜欢
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多