How to invoke the main UI thread from a service

I have a Service class that has an Action<> CallBack sent to it by its clients.

How do I get a call to the Action<> CallBack in the main interface thread so that clients receive a CallBack in the user interface thread. The service does not know anything about WinForms (in fact, it launches an Android application using MonoDroid)

+4
source share
2 answers

It's usually best to leave it in Winforms code to handle streaming. If you want to help, then consider the template used by System.Timers.Timer and FileSystemWatcher, they have the SynchronizingObject property that Winforms code can be set to receive events that are touched by the user interface thread. Make it look like this:

 using System; using System.ComponentModel; class Service { public Action Callback { get; set; } public ISynchronizeInvoke SynchronizationObject { get; set; } public void DoWork() { //... var cb = Callback; if (cb != null) { if (SynchronizationObject == null) cb(); else SynchronizationObject.BeginInvoke(cb, null); } } } 
+1
source

Assuming that you do everything that crosses the scope (WCF, Remoting), you should not pass the delegate as a callback, it just won't work.

Instead, you must define the contracts that the client implements and transfers to the service (WCF has callback agreements ), and then the service will call the callback.

When invoked, the client implementation of the callback is launched. In this implementation, the client makes changes to the user interface. Please note: most callbacks that come through calls within the application are not related to the thread that called them by default; make sure you make your user interface changes by marching the call into the user interface thread.

0
source

All Articles