重复将数据从Windows服务传输到控制台应用程序

时间:2016-12-09 22:17:02

标签: c# .net windows-services

这是我的方案,我有一个每20分钟运行一次任务的Windows服务,任务是:从远程网站托管的API请求更新。

响应是一个JSON对象列表,当服务收到列表时,它会执行一组操作,然后附加更多JSON对象,最后服务必须将列表推送到正在运行的控制台应用程序。

我非常具体的问题:如何将这些数据从Windows服务传输到控制台应用直接专业

直接我指的是没有中间解决方案,比如在临时文件中写入或保存在SQL表中......等等。

专业我指的是最佳的最佳解决方案,尤其是从服务到控制台应用程序的p / Invoke。

3 个答案:

答案 0 :(得分:1)

你肯定需要一种媒介来在这两个过程之间进行交流。通信可以在同一系统上以多种方式完成。

在问题中你的解释看起来像单向沟通。也许你可以通过套接字(原始级别)进行进程间通信或使用消息传递框架进行通信(WCF / SignalR),或者甚至可以使用Message Queue系统(MSMQ / RabbitMQ)等。

如果您可以缩小搜索范围,可以获得具体答案。

答案 1 :(得分:0)

一个漂亮,干净,现代的'这样做的方法是直接在控制台应用程序中托管Web API,并接受JSON输入。

这相对容易设置,并且非常易于测试和使用。

其他方法包括.NET远程处理(不再是现代的),一些其他类型的服务,如WCF,或任何众多的Windows IPC方法。

答案 2 :(得分:0)

我写了一个包含一些适用代码的答案here。基本上,OP需要将Windows窗体应用程序中的字符串发送到控制台应用程序,并让控制台应用程序打印字符串。

我的建议是使用消息队列。

一些快速说明:首先,如果您从未这样做过,可能需要enable the feature in Windows。另外,我想在Windows的某些配置下,您无法直接从C#创建Message Queue;如果是你的情况,你可以手动创建它(或者可能有一种方法可以将它作为安装脚本的一部分或其他东西)。

这是Windows窗体代码:

private void button1_Click(object sender, EventArgs e)
{
    // Or whatever name you end up calling it if you created the queue manually
    const string myQueue = ".\\myQueue";

    // It's possible that this won't work on certain computers
    // If not, you'll have to create the queue manually
    // You'll also need to turn the Message Queueing feature on in Windows
    // See the following for instructions (for Windows 7 and 8): https://technet.microsoft.com/en-us/library/cc730960(v=ws.11).aspx
    if (!MessageQueue.Exists(myQueue))
    {
        MessageQueue.Create(myQueue);
    }

    using (MessageQueue queue = new MessageQueue(myQueue))
    {
        queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
        queue.Send("Test");
    }
}

控制台应用程序:

static void Main(string[] args)
{
    // Or whatever name you use
    const string myQueue = ".\\myQueue";

    // See my comment on the corresponding line in the Windows Forms application
    if (!MessageQueue.Exists(myQueue))
    {
        MessageQueue.Create(myQueue);
    }

    MessageQueue queue = new MessageQueue(myQueue);
    queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });

    while (true)
    {
        Message message = queue.Receive();
        string messageText = message.Body.ToString();

        // Close if we received a message to do so
        if (messageText.Trim().ToLower() == "exit")
        {
            break;
        }
        else
        {
            Console.WriteLine(messageText);
        }
    }
}