1

我有一个由 Windows 服务托管的 WCF 服务。它可以工作,但调用它很慢:一个简单的函数,比如void Test()从客户端调用到服务器接收大约需要 500 毫秒。

我尝试了几种不同的配置,但没有成功地让它更快。客户端和服务器都在同一台机器上。

这是代码:

Shared.dll

[ServiceContract]
public interface IContract
{
    [OperationContract]
    void Test();
}

Server.exe

public class Service : IContract
{
    public void Test()
    {
        this.Log("Test: " + DateTime.Now.TimeOfDay);
    }
}

Client.exe

var binding = ...;
var factory = new ChannelFactory<IContract>(binding, "net.tcp://localhost/Service");
var service = factory.CreateChannel();
this.Log("Test: " + DateTime.Now.TimeOfDay);
service.Test();

app.config

<system.serviceModel>
  <services>
    <service behaviorConfiguration="ServiceBehavior" name="Server.Service">
      <endpoint address="Service" binding="netTcpBinding" bindingConfiguration="NetTcp" contract="Shared.IContract">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
      <host>
        <baseAddresses>
          <add baseAddress="net.tcp://localhost/" />
        </baseAddresses>
      </host>
    </service>
  </services>
  <bindings>
    <netTcpBinding>
      <binding name="NetTcp" portSharingEnabled="true">
        <security mode="None">
          <message clientCredentialType="None"/>
          <transport protectionLevel="None" clientCredentialType="None"/>
        </security>
        <reliableSession enabled="false" />
      </binding>
    </netTcpBinding>
  </bindings>
  <behaviors>
    <serviceBehaviors>
      <behavior name="ServiceBehavior">
        <serviceMetadata httpGetEnabled="false" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

编辑

我目前正在同一台机器上使用客户端和服务器对此进行测试,但想法是将它们放在不同的机器上进行生产。

工厂和渠道创作不是这里的罪魁祸首。我排除Thread.Sleep(20000)在创建和日志之间放置 a 并得到相同的结果。

第一次调用的客户端日志和服务器日志之间的差异大约为 500 毫秒(实际上,它在 300 毫秒到 1 秒之间),但是对于任何更多的调用,它持续不到 5 毫秒Test()。我希望我的函数总是非常快,包括第一次调用。我怎样才能做到这一点?

4

1 回答 1

-1

假设您使用 Datetime.Now 来衡量这一点,我会推荐一种不同的基准测试方法。

    var elapsedTimes = new List<long>();
    var stopwatch = new Stopwatch();

    for (var i = 0; i < 1000; i++)
    {
        stopwatch.Reset();
        stopwatch.Start();

        service.Test();

        stopwatch.Stop();
        elapsedTimes.Add(stopwatch.ElapsedMilliseconds);
    }

    Log("Average time for Test(): " + elapsedTimes.Average() + "ms");

此外,第一次调用似乎总是很慢,可能是因为在服务端进行了初始化。尝试调用 service.Test() 然后运行这个基准测试。

请发布您的结果,我很想知道它是如何进行的。

于 2013-06-21T17:14:56.447 回答