关闭范围和垃圾收集

发布于 2024-09-27 09:05:38 字数 702 浏览 2 评论 0原文

我刚刚编写了一些代码,以便在异步任务处理时间过长的情况下执行超时操作,但我不清楚是否以及何时会处理超时实例(我认为 它会在异步任务及时完成的​​情况下发生,但否则我不知道),或者如果我每次调用此代码时都会累积实例。

//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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丘比特射中我 2024-10-04 09:05:38

目前尚不清楚 timeout 在这里是什么或 DoAsyncTask 做什么,但有一些一般性的要点:

  • 您的 lambda 表达式将捕获 timeout 变量。它不会捕获变量的...因此,如果您稍后在同一方法中将timeout设置为null或其他值,则原始值值不会保存在 lambda 表达式中。
  • 只要委托本身不符合垃圾回收条件,lambda 表达式就会阻止垃圾回收所指的任何 timeout
  • 垃圾回收与处置不同。您谈到“何时处理超时实例” - 什么在调用 Dispose?这不会受到垃圾收集器的影响,除非您依赖于为您调用 Dispose 的终结器。

It's not clear what timeout is here or what DoAsyncTask does, but a few general points:

  • Your lambda expression will capture the timeout variable. It won't capture the value of the variable... so if you have something else later in the same method which sets timeout to null or a different value, the original value won't be held in the lambda expression.
  • The lambda expression will prevent whatever timeout refers to from being garbage collected, so long as the delegate itself isn't eligible for garbage collection
  • Garbage collection isn't the same as disposal. You talk of "when the timeout instance will ever be disposed of" - what's calling Dispose? That won't be affected by the garbage collector, unless you're relying on a finalizer calling Dispose for you.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文