Amgad Serry
Amgad Serry

Reputation: 1625

Windows Phone 8 threading Invalid cross-thread access

I'm making a Tic-Tac-Toe game for Windows Phone 8 and I want the game to play vs itself as a background for the main menu

private Button[] bts;
private List<Button> temp = new List<Button>();
private int[,] winningConditions;
private int counter;
private string Board;

public MainPage()
{
    InitializeComponent();
    bts = new[] { _1, _2, _3, _4, _5, _6, _7, _8, _9 };
    winningConditions = new[,] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 },
    { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
    counter = 0;
    bTextFont();
}

private void NewGame()
{
    foreach (Button i in bts)
        i.Content = "";//here I get an Exception saying Invalid cross-thread access
    while (true)
    {
        NearlyHuman();
        someOneWon();
        counter++;
    }
}
private void form_Loaded(object sender, RoutedEventArgs e)
{
    Thread backGround = new Thread(new ThreadStart(NewGame));
    backGround.Start();
}

Upvotes: 2

Views: 8195

Answers (2)

Sanjith Bravo Dastan
Sanjith Bravo Dastan

Reputation: 449

  • Make use of Background Worker.

For Windows Phone 8: http://msdn.microsoft.com/en-us/library/windows/apps/cc221403(v=vs.105).aspx

Upvotes: 0

nkchandra
nkchandra

Reputation: 5557

You cannot access the UI thread from any other thread directly. So, Encose your UI access code in the Dispatcher.BeginInvoke()

Dispatcher.BeginInvoke(() =>
    {
        foreach (Button i in bts)
           i.Content = "";
    });

Upvotes: 16

Related Questions