Search code examples
c#checkboxinvokerequired

InvokeRequired to checkbox


I just need to create a function to checkbox that will return the current value of checkbox.

I wrote :

private void Checkbox_check()
        {
            if (checkBox1.InvokeRequired)
                return (int)checkBox1.Invoke(new Func<int>(checked));
            else
                return checkBox1.Checked; // bad here i know

        }

What is bad here, can someone just write correctly this function? I need Invoke because can't use in another Thread without invoke. I just search a forum and web about help but can't find solution anywhere.


Solution

  • Don't use Func<> as it doesn't return anything. Use Action instead.

    private void Checkbox_check()
    {
        if (checkBox1.InvokeRequired)
            checkBox1.Invoke(new Action(Checkbox_check));
        else
        {
            // do what you like to do on the ui context
            //  checkBox1.Checked; // bad here i know, yep...
        }
    }
    

    Getting the checked state from another thread, you could do like this:

    private bool Checkbox_check()
    {
        // result value.
        bool result = false;
    
        // define a function which assigns the checkbox checked state to the result
        var checkCheckBox = new Action(() => result = checkBox1.Checked);
    
        // check if it should be invoked.      
        if (checkBox1.InvokeRequired)
            checkBox1.Invoke(checkCheckBox);
        else
            checkCheckBox();
    
        // return the result.
        return result;
    }
    

    I would not advise this, this could lead to deadlocks etc. I advise you to pass the checked value on the threadstart, so you don't have to do any crossthread calls.