Reputation: 2843
I am trying to make my first WCF program. It should be very simple but I can't manage to get it working.
Steps I have done so far:
IWCF.cs code :
using System;
...etc
namespace WCF_Application
{
[ServiceContract]
public interface IWCF
{
[OperationContract]
string DoWork();
}
}
WCF.cs code :
using System;
...
namespace WCF_Application
{
public class WCF : IWCF
{
public string DoWork()
{
return " Hello There! ";
}
}
}
Button code:
private void btnConnect_Click(object sender, EventArgs e)
{
// Starting the Server
ServiceHost svh = new ServiceHost(typeof(WCF));
svh.AddServiceEndpoint(
typeof(IWCF),
new NetTcpBinding(),
"net.tcp://localhost:8000");
svh.Open();
MessageBox.Show("Connected");
// Connecting Client to the server
ChannelFactory<IWCF> scf;
scf = new ChannelFactory<IWCF>(
new NetTcpBinding(),
"net.tcp://localhost:8000");
IWCF s = scf.CreateChannel();
string response = s.DoWork();
MessageBox.Show(response);
svh.Close();
}
I don't get the response message. The program justs freezes. When I trace the code, the program gets stuck at the strong response = s.DoWork();
line.
I also checked netstat -a
in cmd. and it seems the port 8000 does open in listening mode. So the problem should be with the client part.
OS Windows 7 / VS 2010 / C#
Upvotes: 1
Views: 271
Reputation: 3125
You are running into a deadlock issue here because your WCF service is hosted on the same thread as your UI. You could try the following to host the service on another thread.
[ServiceBehavior(UseSynchronizationContext = false)]
public class WCF : IWCF
{
public string DoWork()
{
return " Hello There! ";
}
}
Here is some background on the WPF threading model and UseSynchronizationContext. Alternatively, you could thread off the client calls to your service, but that will likely have other UI updating consequences as well.
Upvotes: 3