nicojs
nicojs

Reputation: 2055

What happens to a disposed Task?

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?

Upvotes: 6

Views: 752

Answers (3)

TomTom
TomTom

Reputation: 62101

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.

Upvotes: 3

Russell Troywest
Russell Troywest

Reputation: 8776

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.

Upvotes: 11

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

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

Upvotes: 1

Related Questions