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.
Asked
Active
Viewed 66 times
1 Answers
1
Cancelling a task won't dispose of anything. I don't really know how you cancel or start your Task
s 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.
-
2I 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