服务结构-CreateServiceInstanceListeners-多个侦听器-“ yield return”或“ return new []”

时间:2019-01-17 15:23:52

标签: azure-service-fabric

如果您的Service Fabric服务具有多个侦听器,我注意到您可以使用2种不同的模式创建CreateServiceInstanceListeners。 (.Net框架/ Statefull /无状态)

第一种方法产生收益,而第二种方法返回数组。

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
    yield return new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint")),
    yield return new ServiceInstanceListener(wcfContext => new WcfCommunicationListener<IWebApi>(wcfServiceObject: this, serviceContext: wcfContext,endpointResourceName: "WcfEndpoint",listenerBinding: WcfUtility.CreateTcpListenerBinding()),"WcfEndpoint")
}

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
    return new[]
    {
        new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint")),
        new ServiceInstanceListener(wcfContext => new WcfCommunicationListener<IWebApi>(wcfServiceObject: this, serviceContext: wcfContext,endpointResourceName: "WcfEndpoint",listenerBinding: WcfUtility.CreateTcpListenerBinding()),"WcfEndpoint")
    };
}

使用一个相对于另一个有什么优势吗?

1 个答案:

答案 0 :(得分:0)

没有太大区别。每个服务实例对返回的可枚举进行一次迭代。

这是从GitHub上的源中摘录的代码。

if (this.instanceListeners == null)
{
    this.instanceListeners = this.userServiceInstance.CreateServiceInstanceListeners();
}

var endpointsCollection = new ServiceEndpointCollection();
var listenerOpenedCount = 0;

foreach (var entry in this.instanceListeners)
{
    var communicationListener = entry.CreateCommunicationListener(this.serviceContext);
    this.AddCommunicationListener(communicationListener);
    var endpointAddress = await communicationListener.OpenAsync(cancellationToken);
    endpointsCollection.AddEndpoint(entry.Name, endpointAddress);
    listenerOpenedCount++;

    var traceMsg = entry.Name.Equals(ServiceInstanceListener.DefaultName)
        ? "Opened communication listener with default name."
        : $"Opened communication listener with name {entry.Name}.";

    ServiceTrace.Source.WriteInfoWithId(TraceType, this.traceId, traceMsg);
}