Winforms Windows窗体应用程序中的WCF主机
hiii 我是WCF新手,我已经在控制台应用程序中编写了一段代码。 我创建了一个这样的服务Winforms Windows窗体应用程序中的WCF主机,winforms,wcf,wcf-hosting,Winforms,Wcf,Wcf Hosting,hiii 我是WCF新手,我已经在控制台应用程序中编写了一段代码。 我创建了一个这样的服务 [ServiceContract] public interface IHelloService { [OperationContract] void SayHello(string msg); } 并定义函数 public class HelloService: IHelloService { public void SayHello(string msg) {
[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);
}
}
static void Main(字符串[]args)
{
IHelloService proxy=ChannelFactory.CreateChannel(新的NetTcpBinding(),新的EndpointAddress(“net。tcp://localhost:9000/HelloWcfService"));
串味精;
while(true)
{
msg=Console.ReadLine();
msg=proxy.SayHello(msg);
Console.WriteLine(“服务器返回”+msg);
}
}
它工作正常,但我想在Windows窗体应用程序中执行相同的操作,并在文本框中显示收到的数据,但我不知道如何执行。
请有人帮帮我,这和您在控制台应用程序中所做的一样。您可以在Load方法中启动ServiceHost,但一个区别是RichTextbox只能在GUI线程中访问,因此您可能必须将GUI SynchronizationContext保存在某个位置,并且当您想要向该RichTextbox输出某些内容时,您需要调用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));
}
}
注意:这只是一个示例,可能不起作用