0

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.

Thewads
  • 4,953
  • 11
  • 55
  • 71
Adamszsz
  • 561
  • 3
  • 13
  • I think the mistake here is that the method returns void, and you return an actual value. – Maarten Mar 17 '17 at 11:45
  • Never write code like this, it is the ultimate threading race bug. Obtain UI values before you start the thread. And make sure that the user cannot change it while the thread is running (use the Enabled property) so that the result you compute in the thread is always consistent with the UI state. BackgroundWorker makes this easy. – Hans Passant Mar 17 '17 at 12:22

2 Answers2

0

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.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
-1

You should write it this way:

private void Checkbox_check()
    {
        if (checkBox1.Invoke:DRequired)
            return (int)checkBox1.Invoke(new Func<int>(checked));
        else
            return checkBox1.Checked.(initInvoke); 
    }
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
sam
  • 1
  • This doesn't look compilable. (1) `return checkBox1.Checked.(initInvoke); ` The method doesn't return an `int` (2) `checkBox1.Checked.(initInvoke); ` Checked is a property, not a function. Dit you test it yourself? – Jeroen van Langen Mar 17 '17 at 11:45