2012-11-28 53 views
2

我正在做一個井字棋遊戲的Windows Phone 8,我想比賽中的發揮VS本身作爲主菜單的Windows Phone 8線程無效跨線程訪問

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

回答

16

背景您無法直接從任何其他線程訪問UI線程。所以,Encose你的UI訪問代碼在Dispatcher.BeginInvoke()

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

感謝了很多,但現在OKY它的工作原理,但仍然問題是,我希望把它像一個活的背景怎麼做呢?如果我做了一個無限循環的程序不會做任何改變,直到它完成,這將永遠不會,所以我應該怎麼做 –