0

I have searched quite a bit looking for how to invoke a control within a if statement for awhile now and haven't been able to find anything on this. I'm sure I'm missing something but if someone could show me how to do this that would be great. Here is a short piece of my code to give you an idea of where my problem is.

if(cardPanelOpponent.GetChildAtPoint(new Point(i, x)) == null)
{
      OpponentCard.Location = new Point(i, x);
      cardPanelOpponent.Invoke(new Action(() => cardPanelOpponent.Controls.Add(OpponentCard))
      break;  }

This line is taking place in a Async environment so I am getting a cross thread exception. How can I run this if statement while on a different thread then the UI.

Timg
  • 227
  • 1
  • 3
  • 12

1 Answers1

1

If your code is running in worker thread then you're not allowed to call GetChildAtPoint or set Location in it. You need to pass the control to UI thread.

if(cardPanelOpponent.InvokeRequired)
{
    cardPanelOpponent.Invoke(new Action(() =>
    {        
        if(cardPanelOpponent.GetChildAtPoint(new Point(i, x)) == null)
        {
              OpponentCard.Location = new Point(i, x);
              cardPanelOpponent.Controls.Add(OpponentCard);
        }        
    });
}

Note: Semantics has changed in above code. We can't add break statement here. So you may need to correct it as your needs.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Okay I have the if statement working but because I can't break it basically gets stuck in a infinite loop. I'm not sure I understand how to get back on the UI thread so that I can break out of the loop after it adds the control and not keep going. Any suggestions? – Timg Mar 10 '14 at 08:54
  • Post your full code of loop, possibly the whole method. I'll try to update my answer accordingly – Sriram Sakthivel Mar 10 '14 at 08:55
  • Okay what I did is create a bool variable and if it adds the control then set it to true. After the Anonymous method I check it and break from there. Appreciate all the help. – Timg Mar 10 '14 at 08:58