关于IDisposable
我正在创建我希望在大多数情况下使用系统资源的界面,但并非总是如此。IDisposable
预计我的界面上的使用包括在内是谨慎的做法吗?
例如,我有一个提供同步方法的接口。
interface IDateTimeProvider : IDisposable
{
int LeapSeconds {get;set;}
DateTime LocalNow {get;}
DateTime UtcNow {get;}
DateTime GpsNow {get;}
}
class NtpTimeProvider : IDateTimeProvider
{
// Assume client is setup and ready to use.
// Obtains time via network resources
NtpClient client;
NtpTimeProvider (int leapSeconds)
{ LeapSeconds = leapSeconds;}
int LeapSeconds {get;set;}
DateTime LocalNow {get{return client.Utc};}
DateTime UtcNow {get{return client.Utc};}
DateTime GpsNow {get{return client.Utc - TimeSpan.FronSeconds(LeapSeconds);}}
void Dispose()
{
if(client != null) Client.Dispose();
}
}
class SystemTimeProvider : IDateTimeProvider
{
SystemTimeProvider (int leapSeconds)
{ LeapSeconds = leapSeconds;}
int LeapSeconds {get;set;}
DateTime LocalNow {get{return DateTime.Now};}
DateTime UtcNow {get{return DateTime.UtcNow };}
DateTime GpsNow {get{return DateTime.UtcNow - TimeSpan.FronSeconds(LeapSeconds);}}
void Dispose()
{ //obviously this isn't needed}
}
所以问题是,IDisposable
当我预计大多数实现将使用需要释放的系统资源时,我应该强加这个要求吗?目前我这样做是因为当 IDateTimeProvider 的用户正在释放资源和
if(myDateTimeProvider is IDisposable) ((IDisposable)myDateTimeProvider).Dispose();
不需要。