目前的代码目前的结构如下:
System.Timers.Timer myTimer;
public void FirstMethod() {
myTimer;= new System.Timers.Timer();
myTimer.start();
SecondMethod();
}
public void SecondMethod(){
//several things happen here and then
myTimer.stop();
}
我被告知我可以使用using
正确地垃圾收集Timer对象。所以我尝试将以下内容应用到我的代码中(取自here):
using (SomeClass someClass = new SomeClass())
{
someClass.DoSomething();
}
我认为以下错误是因为myTimer
无法知道SecondMethod()
?
public void FirstMethod() {
using (System.Timers.Timer myTimer = new System.Timers.Timer())
{
myTimer.start();
SecondMethod();
}
}
public void SecondMethod(){
//several things happen here and then
myTimer.stop();
}
答案 0 :(得分:2)
在有意义的情况下,在IDisposable
块中包装实现using
接口的对象。在这种情况下,它不会,因为该对象必须在更高的范围内有效。请记住,using
语句只是简写(语法糖):
var myDisposableObj = new Whatever();
try
{
// use myDisposableObj. If an exception is thrown
// in here somewhere the call to Dispose() still occurs.
}
finally
{
myDisposableObj.Dispose();
}
在您的情况下,您需要确保在完成对象时调用对象上的Dispose()
(并且以一种方式考虑可能引发的异常,这会阻止对{{1}的调用从发生)。您需要Dispose()
保持一段时间,因此Timer
块不可能。
答案 1 :(得分:2)
如果在using
块结束后应该处置(=销毁)对象,则只能使用using
。计时器通常持续时间长(如示例所示)。
答案 2 :(得分:1)
using
只能用于实现IDisposable
的对象,它将自动放置在使用块的末尾。如果您需要在其他任何地方使用该对象,则无法使用using
。
在您的示例中,您的原始对象不仅不会在其他方法中被识别,而且会被删除。
答案 3 :(得分:1)
是的,你是对的。您的代码是错误的,因为myTimer被声明为局部变量,并且仅在 using 范围内可用。您应该将代码更改为某事。像这样
public void FirstMethod() {
using (System.Timers.Timer myTimer = new System.Timers.Timer())
{
myTimer.start();
SecondMethod(myTimer);
}
}
public void SecondMethod(System.Timers.Timer theTimer){
//several things happen here and then
theTimer.stop();
}
答案 4 :(得分:1)
“使用模式”用于在实现对象不再在范围内时自动调用Dispose。 Dispose用于清理任何非托管资源。 Finalize是垃圾收集器在“收集”对象之前调用的内容。
然而,您可以尝试“强制”收集 -
“可以通过调用Collect强制进行垃圾回收,但大部分时间都应该避免这种情况,因为它可能会产生性能问题。”
所以你需要SecondMethod才能“访问”myTimer?