Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
nicojs Avatar asked Dec 16 '11 11:12

nicojs


1 Answers

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.

like image 80
Russell Troywest Avatar answered Oct 13 '22 02:10

Russell Troywest