C # Change UI from Native Thread

Let the form that contains the textbox and the method to set it (in an unsafe way):

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

      

Now, if I want to make this thread safe, I need to do the following:

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 );
    }
}

      

Right? Now if I want to make the call to SetTextBoxContent () from my own thread possible? As far as I know, there is no way to call a method on an object, so I will instead pass a pointer to a static function in my own code. This function will have a reference to the Form object and make a method call:

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 );
    }
}

      

Now, can I just pass my static CallSetTextBoxContent () function to native code? I read somewhere that I need to create a delegate for this. So I need to create a second type of delegate for CallSetTextBoxContent () and pass this delegate into my own code? 2 types of delegates and 3 functions do something that just seems a little messy. Is it correct?

Thank:)

EDIT: Forgot to mention that I am using Compact framework 2.0

+3


source to share


1 answer


See Marshal.GetFunctionPointerForDelegate and an example here: Sending Callbacks from C # to C ++



+1


source







All Articles