WPF thread and GUI how to access object from different thread?

前端 未结 2 1909
北荒
北荒 2021-02-04 19:08

I have a thread that call an object that get some stuff from Internet. When this object is filled up with all information required, it raises an event with an object will all th

相关标签:
2条回答
  • 2021-02-04 19:51

    I found the solution over this blog.

    Instead of just calling the collection to add the object from the thread.

    queriesViewModel.AddQuery(info);
    

    I have to pass the main thread to the controller and use the dispatcher. Guard answer's was very close.

        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);
            } 
        }
    
    0 讨论(0)
  • 2021-02-04 19:51

    Could a solution be to initialize the object on the main thread?

    MyObject obj;
    
    this.Dispatcher.Invoke((Action)delegate { obj = new MyObject() });
    

    Edit: At a second read-through, this probably isn't a solution given your model. Are you receiving a runtime error as it is? If the object you're passing back is your own, ensuring the object is thread-safe could make CheckAccess unneccessary.

    0 讨论(0)
提交回复
热议问题