我有一个线程调用一个从互联网获取一些东西的对象。当该对象填满所需的所有信息时,它会引发一个事件,其中对象将包含所有信息。该事件由启动线程的控制器消耗。
然后,从事件返回的对象被添加到通过视图模型方法绑定到 GUI 的集合中。
问题是我无法将 CheckAccess 与绑定一起使用...如何解决使用从主线程的其他线程创建的对象的问题?
当我将对象添加到主线程集合时收到的错误是:
这种类型的 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);
}
}
}
我找到了解决方案blog http://blog.guymahieu.com/2006/11/15/systemdelegate-is-not-a-delegate-type/.
而不是仅仅调用集合来从线程中添加对象。
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)