简体   繁体   English

WCF:从服务内部访问Windows窗体

[英]WCF: Accessing a windows form from inside a service

How can I achieve this scenario? 我该如何实现这种情况?

I have a WCF service hosted in a windows form and whenever a client of the service calls a method on the service i want the service to be able to write a message to a textbox on the windows form. 我有一个以Windows窗体形式托管的WCF服务,每当服务的客户端调用服务上的方法时,我希望服务能够将消息写入窗体上的文本框。

I was thinking that i would make my WCF service a Singleton, pass my form using an Interface that the form implements, into the service and then store that instance. 我想我会使我的WCF服务成为Singleton,使用表单实现的接口将我的表单传递到服务中,然后存储该实例。 then when a client calls the service i can simply use the form instance to write to the textbox. 然后,当客户端调用服务时,我可以简单地使用表单实例写入文本框。

I cannot do this of course as i cannot pass a Form into a WCF service. 我无法做到这一点,因为我无法将表单传递给WCF服务。

Any ideas or code samples? 任何想法或代码示例?

The service instance and your Windows form are running in two separate threads, and you cannot just update a UI element on your main UI thread from the service instance. 服务实例和Windows窗体在两个独立的线程中运行,您不能只是从服务实例更新主UI线程上的UI元素。

You need to use a synchronization context and a delegate in order to properly and safely update your UI from the service thread. 您需要使用同步上下文和委托才能从服务线程正确安全地更新UI。

See this CodeProject article - about in the middle, the author talks about the "UI thread woes". 请参阅此CodeProject文章 - 关于中间,作者谈到“UI线程困境”。 That's basically what you need to do: 这基本上是你需要做的:

SendOrPostCallback callback = 
    delegate (object state)
    {   
        yourListBox.Add(state.ToString());
    };

_uiSyncContext.Post(callback, guestName);

See Juval Lowy's MSDN article " WCF Synchronization Contexts " for a comprehensive introduction to the topic. 有关该主题的全面介绍,请参阅Juval Lowy的MSDN文章“ WCF同步上下文 ”。

Hosting a WCF service inside a Winforms app seems like a rather bad idea to me - first of all because of all those threading issues, and secondly, it'll only ever work if the winforms app is up. 在Winforms应用程序中托管WCF服务对我来说似乎是一个相当糟糕的主意 - 首先是因为所有这些线程问题,其次,它只有在winforms应用程序启动时才会工作。 Couldn't you put your WCF service into a console app or a Windows NT Service, and then just create a Winforms based monitoring app, that might check eg a database table for incoming request messages or something? 难道你不能把你的WCF服务放到控制台应用程序或Windows NT服务中,然后只创建一个基于Winforms的监控应用程序,可以检查例如数据库表中是否有传入的请求消息?

Marc

Take a look at this SO answer - as far as I understand it, it is basically the same question. 看看这个SO答案 - 据我所知,它基本上是同一个问题。

You can inject dependencies into WCF services: you just need to implement a custom ServiceHostFactory that wires everything up for you. 可以将依赖项注入WCF服务:您只需要实现一个自定义的ServiceHostFactory,它可以为您提供所有连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM