0

I am reading some files using parallel tasks. During this operation if i cancel the task the file handles are not closed. the tasks are successfully canceled. Looks like i need to do something more to close the file handles during a cancel but not able to figure out what i need to do. I was assuming that the task cancellation will dispose all objects but thats not the case. Any help is much appreciated.

svick
  • 236,525
  • 50
  • 385
  • 514
user55474
  • 537
  • 1
  • 8
  • 25

1 Answers1

1

Cancelling a task won't dispose of anything. I don't really know how you cancel or start your Tasks since you haven't shown any code but the recommended way would be to call the Cancel() method of a task CancellationTokenSource. When your task is then doing what it is supposed to do it should check the tokens property IsCancellationRequested. This post explains the procedure pretty well.

The cleanup is totally up to you. The garbage collector will kill normal objects but you need to call Dispose, Close or the equivalent of any expensive object that you're using.

You have several options for this, calling Dispose manually, using a using block or implementing some sort of unit-of-work pattern.

Community
  • 1
  • 1
Dervall
  • 5,736
  • 3
  • 25
  • 48
  • 2
    I think a better way to test for cancellation is to call [`ThrowIfCancellationRequested()`](http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.throwifcancellationrequested), most of the time. – svick Sep 07 '12 at 10:36