我想警告我的页面传输数据已完成。我创建对象,添加事件处理程序并调用新线程以将异步传输的数据传输到服务器。当数据传输并从服务器应答接收时,我回调我的事件,但抛出异常“无效的跨线程访问”。为什么不运行我的事件处理程序?
// 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
}
}