的Windows Phone 8线程无效跨线程访问 [英] Windows Phone 8 threading Invalid cross-thread access

查看:104
本文介绍了的Windows Phone 8线程无效跨线程访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Windows Phone 8的一个井字棋游戏,我想比赛中的发挥VS本身作为主菜单



<$ P $背景p> 私人按钮[] BTS;
私有列表<按钮和GT;临时=新的List<按钮和GT;();
私人INT [,] winningConditions;
私人诠释柜台;
私人字符串委员会;

公众的MainPage()
{
的InitializeComponent();
BTS =新[] {_1,_2,_3,_4,_5,_6,_7,_8,_9};
winningConditions =新[,] {{0,1,2},{3,4,5},{6,7,8},{0,3,6},
{1, 4,7},{2,5,8},{0,4,8},{2,4,6}};
计数器= 0;
bTextFont();
}

私人无效NewGame()
{
的foreach(按钮,我在BTS)
i.Content =; //这里我得到一个异常说无效的跨线程访问
,而(真)
{
NearlyHuman();
someOneWon();
计数器++;
}
}
私人无效form_Loaded(对象发件人,RoutedEventArgs E)
{
线程后台=新主题(新的ThreadStart(NewGame));
backGround.Start();
}


解决方案

您不能访问UI线程从任何其他线程直接。所以,Encose你的UI访问代码放在Dispatcher.BeginInvoke()

  Dispatcher.BeginInvoke(()=> 
{
的foreach(按钮,我在BTS)
i.Content =;
});


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();
}

解决方案

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 = "";
    });

这篇关于的Windows Phone 8线程无效跨线程访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆