问题描述
|
Thread thread;
OtherMonitor monitor;
public void StartRecieveData()
{
System.Net.IPEndPoint iep = new IPEndPoint(IPAddress.Any,999);
UdpClient client = new UdpClient(iep);
client.Enablebroadcast = true;
string data = null;
while (true)
{
byte[] byteData = client.Receive( ref iep);
data = Encoding.ASCII.GetString(byteData,byteData.Length);
InsertDataToBase(data);
UpdateSecondMonitor(data);
}
}
private void Window_Loaded(object sender,RoutedEventArgs e)
{
monitor = new OtherMonitor();
monitor.Show();
thread = new Thread(new ThreadStart(StartRecieveData));
thread.IsBackground = true;
thread.Start();
}
InsertDataToBase(data) // function inserting record into Database
UpdateSecondMonitor(data) //- opened window on the second monitor,which should be updated
{
monitor.UpdateGrid();
}
在监视器窗口上尝试udate网格时出现的错误和错误:
调用线程无法访问该对象,因为其他线程拥有它
我尝试:
//thread = new System.Threading.Thread(
// new System.Threading.ThreadStart(
// delegate()
// {
// races.dispatcher.Invoke(
// System.Windows.Threading.dispatcherPriority.normal,// new Action(delegate { StartRecieveData(); }));
// }
我不知道如何在“监视器”窗口中更新数据。
有人知道吗?
解决方法
代替
UpdateSecondMonitor(data);
使用
this.Dispatcher.BeginInvoke(new Action<string>((data)=>UpdateSecondMonitor(data)));
确保UI在正确的线程上更新。