关闭范围和垃圾收集
我刚刚编写了一些代码,以便在异步任务处理时间过长的情况下执行超时操作,但我不清楚是否以及何时会处理超时实例(我认为 它会在异步任务及时完成的情况下发生,但否则我不知道),或者如果我每次调用此代码时都会累积实例。
//StartNew creates a new instance of System.Timers.Timer, and
// invokes the ActionOnTimeout after 2000ms, unless calling code
// calls "Stop" first
var timeout = ProcessTimeout.StartNew(() => ActionOnTimeout(), 2000);
//DoAsyncTask creates a new thread, does potentially slow stuff,
/// then invokes this callback
DoAsyncTask(() =>
{
if(timeout.Running)
{
timeout.Stop();
DoCallbackStuff();
}
});
(如果有帮助的话,ProcessTimeout 类使用 System.Timers.Timer
)
I've just written some code to perform a timeout action if an asynchronous task takes too long to process, but what is not clear to me is if and when the timeout instance will ever be disposed of (I think it will in the case where the asynchronous task completes in a timely fashion, but otherwise I've got no idea), or if I'm going to be accumulating instances every time I call this code.
//StartNew creates a new instance of System.Timers.Timer, and
// invokes the ActionOnTimeout after 2000ms, unless calling code
// calls "Stop" first
var timeout = ProcessTimeout.StartNew(() => ActionOnTimeout(), 2000);
//DoAsyncTask creates a new thread, does potentially slow stuff,
/// then invokes this callback
DoAsyncTask(() =>
{
if(timeout.Running)
{
timeout.Stop();
DoCallbackStuff();
}
});
(If it's any help, the ProcessTimeout class uses a System.Timers.Timer
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前尚不清楚
timeout
在这里是什么或DoAsyncTask
做什么,但有一些一般性的要点:timeout
变量。它不会捕获变量的值...因此,如果您稍后在同一方法中将timeout
设置为null或其他值,则原始值值不会保存在 lambda 表达式中。timeout
Dispose
?这不会受到垃圾收集器的影响,除非您依赖于为您调用Dispose
的终结器。It's not clear what
timeout
is here or whatDoAsyncTask
does, but a few general points:timeout
variable. It won't capture the value of the variable... so if you have something else later in the same method which setstimeout
to null or a different value, the original value won't be held in the lambda expression.timeout
refers to from being garbage collected, so long as the delegate itself isn't eligible for garbage collectionDispose
? That won't be affected by the garbage collector, unless you're relying on a finalizer callingDispose
for you.