c# – WPF线程和GUI如何从不同的线程访问对象?

前端之家收集整理的这篇文章主要介绍了c# – WPF线程和GUI如何从不同的线程访问对象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个线程调用一个从Internet获取一些东西的对象.当此对象填满所需的所有信息时,它会引发一个具有对象的事件将所有信息.该事件由启动该线程的控制器使用.

然后将事件中返回的对象添加到通过View Model方法绑定到GUI的集合中.

问题是我不能将CheckAccess与绑定一起使用…如何解决使用从主要的其他线程创建的Object的问题?

我将对象添加到主线程集合时收到的错误是:

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

这个控制器:

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解决方案.

而不是只是调用集合来从线程添加对象.

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);
        } 
    }
原文链接:https://www.f2er.com/csharp/239020.html

猜你在找的C#相关文章