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
}
}
請將代碼發佈在OnCompleted方法中。 – Tudor