WP 7多线程,无效的跨线程访问

时间:2012-10-20 18:38:25

标签: c# multithreading silverlight windows-phone-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
    }
}

1 个答案:

答案 0 :(得分:9)

在Windows Phone 7平台上,所有UI逻辑都应在UI线程上完成。如果您尝试更改可视树,或者在与专用UI线程不同的线程上设置/获取DependencyObject的属性(所有UI元素都是DependencyObject(s)),您将获得无效的跨线程异常。

要在正确的线程上执行UI逻辑,请使用适当的调度程序。

Deployment.Current.Dispatcher.BeginInvoke(() => { <Put your UI logic here> });