如何使用WCF在Windows服务和Windows窗体之间进行通信?

时间:2019-10-23 09:45:39

标签: c# winforms wcf windows-services

此超时后,我有一个超时。我在Windows服务和带有WCF的Windows窗体之间发送了一条消息。

我已经可以从Windows窗体向Windows服务发送消息:

WCF

public class Interact : IInteract
    {
        private Func<string, int> callback;

        public Interact(Func<string, int> callback)
        {
            this.callback = callback;
        }

        public void SendRequest(string name)
        {
            var output = this.callback(name + " callback");
        }

        public string AskIfAlive()
        {
            return "ask";
        }

    }

服务窗口

public partial class LMService : ServiceBase
{
    private ServiceHost host;

    public LMService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Class1.Init();

        Interact instance = new Interact(ReceiveMsg);
        host = new ServiceHost(instance);
        host.Open();

    }

    private int ReceiveMsg(string data)
    {
        // Message from Windows form to windows service
        Log.writeEventLog(data);
        return 1;
    }
}

计时器

public static class Class1
{
    static int Timeout = 0;
    static Timer tm = new Timer();

    public static void Init()
    {
        tm.Interval = 1000;
        tm.Elapsed += Tm_Elapsed;
        tm.Start();
    }

    private static void Tm_Elapsed(object sender, ElapsedEventArgs e)
    {
        Timeout++;
        if(Timeout >= 10)
        {
            // SEND MESSAGE TO WINDOWS FORM
            tm.Stop();
        }
    }

}

我想在Windows服务超时后将某些内容发送到Windows表单,但我不知道该如何做,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用双工服务允许该服务还将消息发送到Windows Forms应用。 有关详细信息和示例,请参见此link

双工服务是WCF服务,它接收可用于向客户端发送消息的回调。除了服务合同之外,您还需要创建服务使用的回调合同。

请注意,回调与WCF操作上下文相关。您可能需要将示例的静态Init方法更改为实例方法,并为每个呼叫/客户端创建Class1的新实例。

答案 1 :(得分:0)

我们设计的服务是双工的还是请求/响应模型。服务的发起者是客户端,因此我们应将服务托管在Windows窗体应用程序中,而不是Windows NT服务中。
此外,您的Windows NT服务似乎一次向Windows Form应用程序发送了一条消息。因此,我认为没有必要使用双工服务。
关于双工服务,我曾经做过一个例子。希望对您有用。
TimeOut exception in WCF while implementing duplex
随时让我知道是否有什么可以帮助您的。