退出范围时,我可以使用C#idisposable来自动化作业吗?
当触发范围时,我可以使用IDISPOSABLE可以自动化工作? 在这种情况下,我正在使用Idisposable可以在方法末尾做一些工作,而不是“处置”资源。 这是我的代码之一:
public class ScopeTimer : IDisposable
{
private Stopwatch sw = new Stopwatch();
private string _logMessage;
public ScopeTimer(string logMessage = "")
{
sw.Start();
_logMessage = logMessage;
}
public void SetMessage(string logMessage)
{
_logMessage = logMessage;
}
void IDisposable.Dispose()
{
sw.Stop();
Logging.Logger.Log($"[{_logMessage}] takes {sw.ElapsedMilliseconds} ms.");
}
}
我正在使用这样的代码:
public void SomeMethod()
{
using var timer = new ScopeTimer();
// do some job
// when method finished, timer.Dispose() is called
}
至少现在,此代码看起来正常,但是在其他许多情况下,这是安全的方法吗?
Can I use IDisposable to do automate job when triggers in exiting the scope?
This case, I am using IDisposable to only do some job in the end of method, not 'disposing' resources.
This is one of my code :
public class ScopeTimer : IDisposable
{
private Stopwatch sw = new Stopwatch();
private string _logMessage;
public ScopeTimer(string logMessage = "")
{
sw.Start();
_logMessage = logMessage;
}
public void SetMessage(string logMessage)
{
_logMessage = logMessage;
}
void IDisposable.Dispose()
{
sw.Stop();
Logging.Logger.Log(quot;[{_logMessage}] takes {sw.ElapsedMilliseconds} ms.");
}
}
and I am using like this :
public void SomeMethod()
{
using var timer = new ScopeTimer();
// do some job
// when method finished, timer.Dispose() is called
}
At least now, this code looks working fine, but is this a safe way in other many circumstances?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,你可以做到。甚至 stephen cleary 在 nito.asyncex 喜欢:
但这是基于意见的。我认为这有助于使代码清洁器,因为您可以设置和恢复状态,并且两个部分相互彼此之间。很容易看到您不会错过任何东西。
缺点是您可能会创建一些需要释放的实例。这可能会给GC带来一些压力。
我们创建了一个结构(不是类)来包装这样的清理代码:
您可以使用此类结构:
是的:是
最后的内存分配,最后是
-struct是不必要的,第二个示例将创建委托。所有这些东西都需要时间和记忆。在性能是真正问题的应用程序中,最好使用普通尝试...最后
块。但是我们也使用 linq ,这也需要上下文对象和代表,没有人在乎。
我认为,明显的正确性比性能更重要,因为快速但错误的结果无济于事。
Yes you can do that. Even Stephen Cleary does it in Nito.AsyncEx like:
But this is opinion based. In my opinion it helps to make code cleaner because you can setup and restore a state and both parts are next to each other. It's easy to see that you don't miss something.
The drawback is that you might create some instances that needs to be freed. That might create some pressure for the GC.
We created a struct (not a class) to wrap such cleanup code:
You can use this like:
Yes the memory allocation for the
Finally
-struct is unnecessary and the second example creates a delegate. All that stuff needs time and memory. In applications where performance is a real issue it might be better to use the normaltry...finally
blocks.But we're also using Linq and this does also need context objects and delegates and nobody cares.
In my opinion, obvious correctness is more important than performance, because a quick but wrong result doesn't help anyone.