Windows Phone 8线程无效的跨线程访问

Amg*_*rry 2 c# multithreading windows-phone-8

我正在为Windows Phone 8制作一个Tic-Tac-Toe游戏,我想让游戏与自己一起作为主菜单的背景

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();
}
Run Code Online (Sandbox Code Playgroud)

nkc*_*dra 16

您无法直接从任何其他线程访问UI线程.所以,在Dispatcher.BeginInvoke()中填充您的UI访问代码

Dispatcher.BeginInvoke(() =>
    {
        foreach (Button i in bts)
           i.Content = "";
    });
Run Code Online (Sandbox Code Playgroud)