已处置的任务会发生什么?

发布于 2024-12-21 13:31:01 字数 528 浏览 5 评论 0原文

当本地任务引用超出范围并且垃圾收集器决定在任务完成之前删除它时,会发生什么情况?

基本上我问的是进行这种服务调用实现是否安全:

/// <summary>
/// Web service operation to start a large batch asynchronously
/// </summary>    
public StartBatchResponseMessage StartBatch(StartBatchRequestMessage request)
{
  Task t = Task.Factory.StartNew(DoWork);
  return new StartBatchResponseMessage();
}

private void DoWork()
{
  // Implement solving world hunger here.
}

在此示例中 DoWork 总是完成吗?即使垃圾收集器决定处置Task实例变量t?

如果没有,实现这种功能的更安全的方法是什么?

What happens to a local Task reference when it runs out of scope and the garbage collector decides to get rid of it before the task completes?

Basically I'm asking if it's safe to make this kind of service call implementation:

/// <summary>
/// Web service operation to start a large batch asynchronously
/// </summary>    
public StartBatchResponseMessage StartBatch(StartBatchRequestMessage request)
{
  Task t = Task.Factory.StartNew(DoWork);
  return new StartBatchResponseMessage();
}

private void DoWork()
{
  // Implement solving world hunger here.
}

Will DoWork always complete in this example? Even if the garbage collector decides to dispose the Task instance variable t?

If not, what is a safer way to implement this kind of functionality?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

浅语花开 2024-12-28 13:31:01

是的,它将被运行。如果反编译代码,您可以看到对 Task.Factory.StartNew 的调用调用 Task.InternalStartNew,后者又调用 Task.ScheduleAndStart(false)

这又调用task.m_taskScheduler.QueueTask(this),根据MSDN 将任务添加到内部结构中 - 这当然会阻止它被垃圾收集。这正是您所希望的。

yes, it will be run. If you decompile your code you can see the call to Task.Factory.StartNew calls Task.InternalStartNew, which calls Task.ScheduleAndStart(false).

This in turn calls task.m_taskScheduler.QueueTask(this), which according to MSDN adds the task to an internal structure - which will of course stop it from being garbage collected. Which is exactly as you'd hope.

孤独难免 2024-12-28 13:31:01

常识,你知道。任务库必须以某种方式调用您的方法,因此 - 它必须保留引用,否则它无法调用它。所以,显然,这个引用会阻止垃圾收集。

基本上,您获得的“任务”是指向内部执行引擎也必须引用的任务对象的指针,否则它将永远不会被执行。

因此,由于除了 t 变量之外还有其他引用,因此它不会被处理。

Common sense, you know. The Task library has to somehow call your method, so - it has to keep a reference, otherwise it could not call it. So, obviously, this reference prevents garbage collection.

Basically the "Task" you get is your pointer to the Task object that the internal execution engine also has to have a reference to, otherwise it would never get executed.

So, as there are references OTHER than your t variable, so it won't be disposed.

抱猫软卧 2024-12-28 13:31:01

是的,任务总会完成。当任务运行时,垃圾收集器不会到达其相关部分。

Yes, the task will always complete. The garbage collector is not going to get to its relevant parts while the task is running.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文