[英]WPF thread and GUI how to access object from different thread?
我有一個線程調用一個從Internet獲取一些東西的對象。 當此對象填滿所需的所有信息時,它會引發一個具有對象的事件將所有信息。 該事件由啟動該線程的控制器使用。
然后將事件中返回的對象添加到通過View Model方法綁定到GUI的集合中。
問題是我不能將CheckAccess與綁定一起使用...如何解決使用從主要的其他線程創建的Object的問題?
我將對象添加到主線程集合時收到的錯誤是:
這種類型的CollectionView不支持從與Dispatcher線程不同的線程更改其SourceCollection。
這個控制器:
public class WebPingerController
{
private IAllQueriesViewModel queriesViewModel;
private PingerConfiguration configuration;
private Pinger ping;
private Thread threadPing;
public WebPingerController(PingerConfiguration configuration, IAllQueriesViewModel queriesViewModel)
{
this.queriesViewModel = queriesViewModel;
this.configuration = configuration;
this.ping = new Pinger(configuration.UrlToPing);
this.ping.EventPingDone += new delPingerDone(ping_EventPingDone);
this.threadPing = new Thread(new ThreadStart(this.ThreadedStart));
}
void ping_EventPingDone(object sender, QueryStatisticInformation info)
{
queriesViewModel.AddQuery(info);//ERROR HAPPEN HERE
}
public void Start()
{
this.threadPing.Start();
}
public void Stop()
{
try
{
this.threadPing.Abort();
}
catch (Exception e)
{
}
}
private void ThreadedStart()
{
while (this.threadPing.IsAlive)
{
this.ping.Ping();
Thread.Sleep(this.configuration.TimeBetweenPing);
}
}
}
我在這個博客上找到了解決方案。
而不是只是調用集合來從線程添加對象。
queriesViewModel.AddQuery(info);
我必須將主線程傳遞給控制器並使用調度程序。 警衛的答案非常接近。
public delegate void MethodInvoker();
void ping_EventPingDone(object sender, QueryStatisticInformation info)
{
if (UIThread != null)
{
Dispatcher.FromThread(UIThread).Invoke((MethodInvoker)delegate
{
queriesViewModel.AddQuery(info);
}
, null);
}
else
{
queriesViewModel.AddQuery(info);
}
}
解決方案是初始化主線程上的對象嗎?
MyObject obj;
this.Dispatcher.Invoke((Action)delegate { obj = new MyObject() });
編輯 :在第二次閱讀時,這可能不是給定模型的解決方案。 您是否收到運行時錯誤? 如果您傳回的對象是您自己的對象,確保該對象是線程安全的,可能會使CheckAccess不再需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.