我想实现一个非常简单的IDisposable
。
整个想法是测量我的方法的执行时间,它们都返回一个 MethodResult
。例如
public class MethodResult : IDisposable
{
private Stopwatch _StopWatch;
public MethodResult()
{
_StopWatch = new Stopwatch();
_StopWatch.Start();
}
public object Result { get; set; }
public TimeSpan ExecutionTime { get; set; }
public void Dispose()
{
_StopWatch.Stop();
ExecutionTime = _StopWatch.Elapsed;
}
}
用法:
static MethodResult TestMehodResult()
{
using (var result = new MethodResult())
{
result.Result = 666;
Thread.Sleep(1000);
return result;
}
}
我的问题非常简单:对于这种情况,仅实现 Dispose()
方法就足够了,还是我应该实现整个 Dispose
pattern在我的课上?
我的类(class)没有资源可供免费使用。
奖励问题:是否有更好的模式来测量方法的执行时间,而不是像我那样使用 IDisposable
?
对不起,如果这个问题很愚蠢。我是 .net 的新手
提前致谢。
最佳答案
为了忠实于作用域的概念,您可以将结果注入(inject) IDisposable
的构造函数中。使用接口(interface)来保持灵 active 。我很惊讶没有人提到您的方法中类型安全的损失,我肯定会将泛型类型参数添加到基 MethodResult
类中(正如您在评论中提到的那样)。
public interface ITimed
{
TimeSpan ExecutionTime { get; set; }
}
public class MethodResult<T> : ITimed
{
public T Result { get; set; }
public TimeSpan ExecutionTime { get; set; }
}
public class MethodTimer : IDisposable
{
private readonly Stopwatch _StopWatch;
private ITimed _result;
public MethodTimer(ITimed result)
{
_result = result;
_StopWatch = new Stopwatch();
_StopWatch.Start();
}
public void Dispose()
{
_StopWatch.Stop();
_result.ExecutionTime = _StopWatch.Elapsed;
_result = null;
}
}
用法
static MethodResult<int> TestMehodResult()
{
var timedResult = new MethodResult<int>();
using (var timer = new MethodTimer(timedResult))
{
timedResult.Result = 666;
Thread.Sleep(1000);
}
return timedResult;
}
关于c# - 实现一个非常基本的 IDisposable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361280/