Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP 7 multithreading, invalid cross-thread access

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
    }
}
like image 504
Illia Lavrik Avatar asked Oct 20 '12 18:10

Illia Lavrik


Video Answer


1 Answers

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> }); 
like image 125
Eilistraee Avatar answered Oct 03 '22 07:10

Eilistraee