【问题标题】:How can I make two process comunicate?如何使两个进程通信?
【发布时间】:2011-07-19 16:16:23
【问题描述】:

我有两个 .net 应用程序。一个是普通的 Windows 窗体应用程序,而另一个是 Microsoft Word COM 插件。我正在使用 C# 开发这两个应用程序。

我需要这两个应用程序来相互通信。我想知道实现这一目标的最佳方法是什么。

我想到的第一件事是我应该使用双向命名管道来执行此操作,但命名管道是系统范围的,我需要将连接限制为在同一会话中运行进程(这可以而且将会在终端服务器上使用)。

有没有办法将命名管道限制在当前会话中?如果没有我有什么选择?

谢谢

【问题讨论】:

  • 好的,这是一个在黑暗中愚蠢的镜头:套接字可以工作吗?
  • 我认为他们不会,因为我将在同一台机器上的不同会话中运行多个服务器(终端服务器设置)。我怎么知道要连接哪一个?
  • 我们在这里谈论什么样的沟通。实时,一次,在某个时间间隔?您发送纯文本、对象、xml 的数据类型是什么?
  • 我需要传输对象,但我想我可以将对象转换为 xml 或文本。我希望传输是即时的,因为用户将在一个应用程序中启动传输并期望另一个应用程序立即响应。
  • 这种“瞬时”是一次性的,还是会在应用程序之间返回和第四次?

标签: .net named-pipes inter-process-communicat


【解决方案1】:

您可以创建一个本地网络服务来实现这一点。

要创建您的网络服务,您必须执行以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService1
{        
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        public int myInt = 0;

        [WebMethod]
        public int increaseCounter()
        {
            myInt++;
            return myInt;
        }

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

    }
}

当您运行您的网络服务时,您应该会看到如下内容:

在不同的程序/线程上(在本例中为控制台应用程序)

您应该能够连接到该服务:

最后输入你刚刚创建的服务的url:

现在您可以从该控制台应用程序中实例化该类 Service1 的对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication36
{
    class Program
    {
        static void Main(string[] args)
        {
            localhost.Service1 service = new localhost.Service1();

            // here is the part I don't understand..
            // from a regular class you will expect myInt to increase every time you call
            // the increseCounter method. Even if I call it twice I always get the same result.

            int i;
            i=service.increaseCounter();

            Console.WriteLine(i.ToString());

            // you can recive string data as:
            string s = service.HelloWorld();

            // output response from other program
            Console.WriteLine(s);

            Console.Read();


        }
    }
}

使用这种技术,您将能够将大部分内容传递给您的其他应用程序(任何可序列化的内容)。因此,也许您可​​以将此 Web 服务创建为第三个线程,以使其更有条理。希望这会有所帮助。

【讨论】:

  • 您好,感谢您的回答,您已经付出了很多努力。但是,几个月前我通过使用双向 WCF 服务解决了这个问题,我认为这是一个更好的解决方案。它就像一个网络服务,但它托管在我的 .net 应用程序中。
  • 我的答案来自:stackoverflow.com/q/7589301/637142。只是修改得很少。谢谢,这是一个更好的解决方案,看起来很有趣。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 2011-08-22
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多