WPF thread and GUI How to access an object from different threads?

I have a thread that calls an object that receives some things from the Internet. When this object is filled with all the necessary information, it triggers an event with the object, all data will be displayed. The event is consumed by the controller that started the thread.

The returned object from the event is added to the collection, which is bound to the graphical interface using the View Model approach.

The problem is that I cannot use CheckAccess with binding ... how can I fix the problem of using Object that was created from another main thread?

The error I get when I add an object to the main thread collection:

This type of CollectionView does not support changes to the SourceCollection from a stream other than the Dispatcher stream.

This is the controller:

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); } } } 
+6
c # wpf
source share
2 answers

I found a solution over this blog .

Instead of just calling a collection to add an object from the stream.

 queriesViewModel.AddQuery(info); 

I need to transfer the main thread to the controller and use the dispatcher. The answer to the guard 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); } } 
+6
source share

Can a solution initialize an object in the main thread?

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

Change On a second read, this is probably not the solution to your model. Do you get a runtime error as is? If the object you are passing back is your own, ensuring that the object is thread safe can make CheckAccess unnecessary.

+3
source share

All Articles