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

1 回答 1

9

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

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

Deployment.Current.Dispatcher.BeginInvoke(() => { <Put your UI logic here> }); 
于 2012-10-20T18:48:58.567 回答