Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top