2

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

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

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

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

谢谢

4

1 回答 1

0

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

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

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 服务创建为第三个线程,以使其更有条理。希望这可以帮助。

于 2011-10-21T03:51:45.357 回答