Windows窗体应用程序中的WCF主机



hiii我是WCF的新手,我已经在Console应用程序中编写了一段代码。我创建了一个类似的服务

[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中显示收到的数据,但我不知道如何做到这一点。请有人帮我

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


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

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

最新更新