【问题标题】:WCF host in Windows Form ApplicationWindows 窗体应用程序中的 WCF 主机
【发布时间】:2011-08-19 09:15:20
【问题描述】:

hiii 我是 WCF 的新手,我已经在控制台应用程序中编写了代码。 我已经创建了这样的服务

[ServiceContract]
public interface IHelloService
{
    [OperationContract]
    void SayHello(string msg);
}

并定义函数

public class HelloService: IHelloService 
{
    public void SayHello(string msg)
    {
       Console.WriteLine("I rec message : " + msg); 

    }
}

我正在从主程序文件开始服务

static void Main(string[] args)
{
        Console.WriteLine("******* Service Console *******");
        using(ServiceHost host = new ServiceHost(typeof(HelloWcfServiceLibrary.HelloService)))
        {

            host.AddServiceEndpoint(typeof(IHelloService), new NetTcpBinding(), "net.tcp://localhost:9000/HelloWcfService");
            host.Open();
            Console.Read();
        }
 }

在客户端的代码是

 static void Main(string[] args)
 {
        IHelloService proxy = ChannelFactory<IHelloService>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloWcfService"));
        string msg;
        while (true)
        {
            msg = Console.ReadLine();
            msg = proxy.SayHello(msg);
            Console.WriteLine("Server returned " + msg);
        }
  }

它工作正常,但我想在 Windows 窗体应用程序中做同样的事情,并在 Richtextbox 中显示接收到的数据,但我不知道该怎么做。 请有人帮助我

【问题讨论】:

    标签: winforms wcf wcf-hosting


    【解决方案1】:

    这与您在控制台应用程序中所做的相同。您可以在 Load 方法中启动 ServiceHost,但一个区别是 RichTextbox 只能在 GUI 线程中访问,因此您可能必须将 GUI SynchronizationContext 保存在某处,并且当您想向该富文本框输出某些内容时,您需要调用 Post方法或在 SynchronizationContext 上发送,例如:

    
    public class HelloService: IHelloService {    
    private SynchronizationContext context;
    private RichTextbox textbox;
    public void SayHello(string msg)   
    {       
    context.Post((obj) => textbox.Add("I rec message : " + msg));
    }
    }
    

    注意:这只是一个示例,它可能不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多