gpt4 book ai didi

wcf - ChannelFactory:创建和处置

转载 作者:行者123 更新时间:2023-12-02 00:37:17 24 4
gpt4 key购买 nike

我编写了一个供 WPF 客户端使用的 Sdk,负责调用 WCF 服务和缓存。这些 WCF 服务是使用 ChannelFactory 调用的,因此我没有服务引用。为此,我创建了一个工厂来处理打开和关闭 ChannelFactory 和 ClientChannel,如下所示:

public class ProjectStudioServiceFactory : IDisposable
{
private IProjectStudioService _projectStudioService;
private static ChannelFactory<IProjectStudioService> _channelFactory;

public IProjectStudioService Instance
{
get
{
if (_channelFactory==null) _channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
_projectStudioService = _channelFactory.CreateChannel();
((IClientChannel)_projectStudioService).Open();
return _projectStudioService;
}
}

public void Dispose()
{
((IClientChannel)_projectStudioService).Close();
_channelFactory.Close();
}
}

我调用的每个请求都是这样的:

 using (var projectStudioService = new ProjectStudioServiceFactory())
{
return projectStudioService.Instance.FindAllCities(new FindAllCitiesRequest()).Cities;
}

虽然这可行,但速度很慢,因为对于每个请求,客户端 channel 和工厂都会打开和关闭。如果我保持打开状态,它会非常快。但我想知道最佳做法是什么?我应该保持打开状态吗?或不?如何正确处理?

最佳答案

谢谢 Daniel,没看到那个帖子。所以我想以下可能是一个不错的方法:

public class ProjectStudioServiceFactory : IDisposable
{
private static IProjectStudioService _projectStudioService;
private static ChannelFactory<IProjectStudioService> _channelFactory;

public IProjectStudioService Instance
{
get
{
if (_projectStudioService == null)
{
_channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
_projectStudioService = _channelFactory.CreateChannel();
((IClientChannel)_projectStudioService).Open();
}
return _projectStudioService;
}
}

public void Dispose()
{
//((IClientChannel)_projectStudioService).Close();
//_channelFactory.Close();
}
}

关于wcf - ChannelFactory:创建和处置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4112684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com