3

我编写了一个由 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;
        }

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

4

1 回答 1

3

谢谢丹尼尔,没看到那个帖子。所以我想以下可能是一个好方法:

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();
    }       
}
于 2010-11-06T18:57:28.840 回答