Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Modify UI from native thread

Let a form that contains a text box and a 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 what if i want to make calling SetTextBoxContent() from a native thread possible ? As far as i know there is no way of calling an object's methods, so instead i would pass a pointer to a static function into the native code. This function would have a reference to the Form object and perform the method call itself :

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 function CallSetTextBoxContent() into the native code ? I read somewhere that i need to create a delegate for this. So that means i need to create a second type of delegate for CallSetTextBoxContent() and pass this delegate to the native code ? 2 delegate types and 3 functions to do something that simple seems a bit messy. Is it the right way ?

Thank you :)

EDIT : Forgot to mention that i'm using compact framework 2.0

like image 735
Virus721 Avatar asked Jan 22 '26 06:01

Virus721


1 Answers

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

like image 180
Andrei Tătar Avatar answered Jan 23 '26 20:01

Andrei Tătar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!