2012-10-20 73 views
7

我想警告我的頁面傳輸的數據已完成。我創建對象,添加事件處理程序,並將異步傳輸數據的新線程調用到服務器。當數據傳輸,並從服務器回答我回調我的事件,但拋出異常'無效的跨線程訪問'。 爲什麼不運行我的事件處理程序?WP 7多線程,無效的跨線程訪問

// My page (PhoneApplicationPage) 
public partial class PageStart 
{ 
    private void btn_Send_Click(object sender, RoutedEventArgs e) 
    { 
      TransmitHolder holder = new TransmitHolder(); 
      holder.onCompleted += new TransmitHolder.CompleteHandler(onCompleted); 
      // transmit async 
      new Thread(delegate() { Transmitter(holder).Start(); }).Start(); 
    } 

    private void onCompleted(object sender, byte[] answer) 
    { 
      //some code 
    } 
} 

public class TransmitHolder 
{ 
    public delegate void CompleteHandler(object sender, byte[] answer); 
    public event CompleteHandler onCompleted; 

    public void Complete(byte[] answer) 
    { 
     if (onCompleted != null) 
     { 
      onCompleted(null, answer); // here throw exception `invalid cross-thread access` 
     } 
    } 
} 

public class Transmitter 
{ 
    private TransmitHolder holder; 

    public Transmitter(TransmitHolder holder) 
    { 
     this.holder = holder; 
    } 

    // send data from server 
    public void Start() 
    { 
     // send data using soket 
     NetworkManager nm = new NetworkManager(); 
     // method Send execute Connect, Send and Recive data from server 
     byte[] answer = nm.Send(Encoding.UTF8.GetBytes("hello_word")); 
     holder.Complette(answer); // notify, send data completed 
    } 
} 
+2

請將代碼發佈在OnCompleted方法中。 – Tudor

回答

9

在Windows Phone 7平臺上,所有UI邏輯都應該在UI線程上完成。如果您嘗試更改可視化樹,或者在與專用UI線程不同的線程上設置/獲取DependencyObject的屬性(所有UI元素都是DependencyObject(s)),您將得到一個無效的交叉線程異常。

要在正確的線程上執行UI邏輯,請使用適當的調度程序。

Deployment.Current.Dispatcher.BeginInvoke(() => { <Put your UI logic here> });