How to Call the Main UI Thread from a Service
I have a 开发者_运维知识库Service class which has an Action<> CallBack
sent to it by its clients.
How do I have the service call the Action<> CallBack
on the Main UI thread so clients get the CallBack on the UI thread. The service knows nothing about WinForms (It's actually running an an Android App using MonoDroid)
It is usually better to leave it up to the Winforms code to deal with the threading. If you want to help then consider the pattern used by System.Timers.Timer and FileSystemWatcher, they have a SynchronizingObject property that the Winforms code can set to get events raised on the UI thread. Make it look similar to 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);
}
}
}
Assuming that you are doing anything that crosses the application domain (WCF, Remoting), you shouldn't pass a delegate as a callback, it simply won't work.
Instead, you have to define contracts which the client implements and passes to the service (WCF has callback contracts) and then the service will call the callback.
When called, the client's implementation of the callback will be triggered. It's in that implementation that the client makes the change to the UI. Note, most callbacks that come through intra-app-domain calls are not on the thread that called them by default; make sure to perform your UI changes by marshaling a call to the UI thread.
精彩评论