WCF服务超时
问题描述:
我正在创建一个WCF服务,并且在我的一些集成测试中使用它时会超时。我已经能够缩小它的范围,并通过以下代码进行演示。看起来在创建主机之前创建一个表单会导致问题,但我不知道为什么。WCF服务超时
class Program
{
[ServiceContract]
public interface IMyContract
{
[OperationContract]
void Ping();
}
public class MyContract : IMyContract
{
public void Ping()
{
Console.WriteLine("Ping");
}
}
public class MyContractProxy : ClientBase<IMyContract>, IMyContract
{
public MyContractProxy(int port)
: base(new NetTcpBinding { SendTimeout = TimeSpan.FromSeconds(5) }, new EndpointAddress(string.Format("net.tcp://localhost:{0}", port)))
{
}
public void Ping()
{
Channel.Ping();
}
}
static void Main(string[] args)
{
try
{
new Form();
var host = new ServiceHost(typeof(MyContract));
host.AddServiceEndpoint(typeof(IMyContract), new NetTcpBinding(), "net.tcp://localhost:12345");
host.Open();
var proxy = new MyContractProxy(12345);
proxy.Open();
proxy.Ping();
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
}
答
表单更改您的服务的行为 - 您的代理和服务在同一个线程中运行。
在UI线程和非UI线程中托管服务存在差异。当您在非UI线程中托管服务时,服务将创建新线程来处理请求。如果您在UI线程中托管服务(如果您在那里运行任何WinForm或WPF表单,它就会发生),默认情况下它不会使用新线程。相反,它将处理接收的呼叫作为标准Windows消息循环的一部分。
添加ServiceBehavior避免这种行为:
[ServiceBehavior(UseSynchronizationContext=false)]
public class MyContract : IMyContract
{ ... }
+0
这正是问题所在。谢谢! – 2010-09-16 14:29:59
什么错误讯息显示?如果你根本没有创建表单,它是否仍然超时? – Bernard 2010-09-15 18:54:33
你的配置文件是什么样的?看到这可能也有帮助。 – 2010-09-15 19:01:59