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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With