wpf线程错误
本文关键字:错误 线程 wpf | 更新日期: 2023-09-27 17:57:40
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, 0, 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在正确的线程上更新。