I want warn my page that the transmitted data is completed. I create object, add event handler and call new Thread for async transmitted data to server. When data transmitted, and recive from server answer i callback my event, but throw exception 'invalid cross-thread access'. Why don't run my event handler?
// 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
}
}
On the Windows Phone 7 Platform, all the UI logic should be done on the UI Thread. If you attempt to change the visual tree, or set/get a property of a DependencyObject (all the UI elements are DependencyObject(s) ) on a thread different thant the dedicated UI thread, you will get an Invalid Cross thread exception.
To perform UI logic on the right thread, use the adequate dispatcher.
Deployment.Current.Dispatcher.BeginInvoke(() => { <Put your UI logic here> });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With