简体   繁体   中英

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
    }
}

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> }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM