문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top