【发布时间】:2010-09-30 17:18:32
【问题描述】:
我正在使用 Topshelf 将 WCF 服务托管为 Windows 服务。即使只是在控制台上运行,在我向其发送 Ctrl-C 后,它也需要很长时间才能关闭,这在作为服务运行时会被镜像。在我的本地机器上,调用 svcHost.Close(new TimeSpan(0)) 需要 1 毫秒,但在 Topshelf 调用的 Stop 方法结束和代码退出 Runner.Host() 方法之后需要 10240 毫秒。这不是很好,但是在我尝试过的生产服务器上,第二个值是 70s。这远远超过了 Windows 在确定服务是垃圾之前提供服务的 30 秒。
这是我的 Topshelf 代码和服务代码。我已经将两者都剥离了很多以删除 Log4Net 日志记录和异常处理,因为我已经验证没有发生异常。
public class Service
{
private ServiceHost svcHost;
public void Start()
{
string bindUri = "net.tcp://MyMachineName:10000";
svcHost = new ServiceHost(typeof(MyServiceClass));
svcHost.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding("tcp"), bindUri);
svcHost.Description.Behaviors.Add(new LoggerBehavior());
svcHost.Open();
}
public void Stop()
{
svcHost.Close(new TimeSpan(0));
svcHost = null;
}
}
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
var cfg = RunnerConfigurator.New(c =>
{
c.ConfigureService<Service>(s =>
{
s.Named("MyServiceName");
s.HowToBuildService(x => new Service());
s.WhenStarted(service => service.Start());
s.WhenStopped(service =>
{
sw.Start();
service.Stop();
sw.Stop();
Console.WriteLine("Stop Time: {0}ms", sw.ElapsedMilliseconds); // usually 1-2ms
sw.Reset();
sw.Start();
});
});
c.RunAsLocalSystem();
c.SetDescription("Runs MyServiceName.");
c.SetDisplayName("MyServiceName");
c.SetServiceName("MyServiceName");
});
Runner.Host(cfg, args);
sw.Stop();
// ~10 seconds on my machine, ~70s on a production server!
Console.WriteLine("Finish Time: {0}ms", sw.ElapsedMilliseconds);
}
}
超过 10 秒和超过 70 秒似乎太“默认”了,所以我搜索了高低的超时设置以尽可能低,但它们似乎都没有任何好处。这是我的 app.config 代码。
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="tcp"
maxReceivedMessageSize="52428800"
transferMode="Buffered"
openTimeout="0:00:01"
sendTimeout="0:00:01"
receiveTimeout="0:00:01"
closeTimeout="0:00:01">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="100" maxConcurrentInstances="100" maxConcurrentSessions="100" />
<serviceTimeouts transactionTimeout="0:00:01" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyApp.MyServiceClass" behaviorConfiguration="MyServiceBehavior">
<host>
<timeouts openTimeout="0:00:01" closeTimeout="0:00:01" />
</host>
</service>
</services>
</system.serviceModel>
那么我该怎么做才能让 WCF 更快地关闭?
【问题讨论】:
-
您知道您使用的 Topshelf 版本吗?
-
程序集版本为 2.1.0.0。我昨天把它从github.com/Topshelf/Topshelf/commits/develop 拉下来(所以是 9/29 版本)并构建了它,因为我需要修复 /instance: 标志。
标签: c# .net wcf windows-services topshelf