我想知道保留一个RegistryManager实例而不是在每个方法中创建一个新实例是否是一个好习惯。
只是为了给出更多解释,它会产生差异,因为如果我保留一个实例而不是在每个方法中创建一个实例,我必须向我的树的所有级别公开一个Dispose方法。
为了解决我的问题,下面的代码展示了两种方法:
1 - 处理模式方法(我想避免):
public class IOTHubDeviceService : IDispose {
private RegistryManager _registryManager;
public IOTHubFacade(string iotHubConnectionString)
{
_registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
}
public async Task<Device> AddDeviceAsync(Device device)
{
return await _registryManager.AddDeviceAsync(device);
}
public void Dispose()
{
_registryManager.CloseAsync();
}
}
public class DeviceRegistration : IDisposable {
private IOTHUBDeviceService iotHubService;
public DeviceRegistration() {
iotHubService = new IOTHUbDeviceService("xxxx")
}
public void AddDevice(Device device){
iotHubService.AddDeviceAsync(device);
}
public void Dispose(){
iotHubService.Dispose();
}
}
2 - “使用”声明方法:
public class IOTHubDeviceService {
private string _iotHubConnectionString;
public IOTHubFacade(string iotHubConnectionString)
{
_iotHubConnectionString = iotHubConnectionString;
}
public async Task<Device> AddDeviceAsync(Device device)
{
using(var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString))
{
return await registryManager.AddDeviceAsync(device);
}
}
}
public class DeviceRegistration {
private IOTHUBDeviceService iotHubService;
public DeviceRegistration() {
iotHubService = new IOTHUbDeviceService("xxxx")
}
public void AddDevice(Device device){
iotHubService.AddDeviceAsync(device);
}
}
我想知道哪两种方法更好。 谢谢!
答案 0 :(得分:0)
.Net Framework提供了应该实现的System.IDisposable接口,以便为开发人员提供一种手动方式,以便在不需要时立即释放非托管资源。垃圾收集器(GC)无法自动释放非托管资源,它旨在管理托管资源,例如使用C#操作符new
分配的内存。
处理对象的模式(称为dispose pattern)对对象的生命周期强制执行。
为了更好地理解,您可以参考以下主题:
我认为保留RegistryManager实例是一种很好的做法,因为它使用非托管资源,例如网络连接。也许以下代码更好。
public class IOTHubDeviceService : IDispose {
private RegistryManager _registryManager;
public IOTHubFacade(string iotHubConnectionString)
{
_registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
}
public async Task<Device> AddDeviceAsync(Device device)
{
return await _registryManager.AddDeviceAsync(device);
}
public void Dispose()
{
if(_registryManager != null){
_registryManager.CloseAsync();
_registryManager.Dispose();
_registryManager = null;
}
}
}
public class DeviceRegistration : IDisposable {
private IOTHUBDeviceService iotHubService;
public DeviceRegistration() {
iotHubService = new IOTHUbDeviceService("xxxx")
}
public void AddDevice(Device device){
iotHubService.AddDeviceAsync(device);
}
public void Dispose(){
if(iotHubService != null){
iotHubService.Dispose();
iotHubService = null;
}
}
}