如何从服务调用主 UI 线程

发布于 2024-11-29 11:31:47 字数 196 浏览 0 评论 0原文

我有一个 Service 类,它有一个 Action<> CallBack 由其客户端发送给它。

如何让服务调用 Action<> CallBack 在主 UI 线程上,以便客户端在 UI 线程上获取回调。该服务对 WinForms 一无所知(它实际上是使用 MonoDroid 运行 Android 应用程序)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生生漫 2024-12-06 11:31:47

通常最好让 Winforms 代码来处理线程。如果您想提供帮助,请考虑 System.Timers.Timer 和 FileSystemWatcher 使用的模式,它们有一个 SynchronizingObject 属性,Winforms 代码可以设置该属性来获取 UI 线程上引发的事件。让它看起来类似于这样:

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);
        }
    }
}

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);
        }
    }
}
燃情 2024-12-06 11:31:47

假设您正在执行任何跨应用程序域(WCF、远程处理)的操作,则不应将委托作为回调传递,因为它根本不起作用。

相反,您必须定义客户端实现并传递给服务的合同(WCF 有 回调合约),然后服务将调用回调。

当调用时,客户端的回调的实现将会被触发。客户端正是在该实现中对 UI 进行更改的。请注意,大多数通过应用程序域内调用进行的回调不在默认情况下调用它们的线程上;确保通过封送对 UI 线程的调用来执行 UI 更改。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文