Troubleshooting tips

Suppose I have a processor whose task is to save files to disk. This runs as a Task , observing the BlockingCollection<T> for the files being processed.

When a task is canceled and there are still files that need to be saved to disk, what would be good practice for this?

It would be convenient if the task right before the output quickly wrote the remaining files to disk, although I am not sure that this contradicts the philosophy of canceling the task (since cancellation should be performed as quickly as possible).

Another option is the second procedure after the cancellation of the task, the task of which is to write the remaining files to disk.

Code example:

 class FileProcessor { private readonly BlockingCollection<Stream> input; public FileProcessor(BlockingCollection<Stream> input) { _input = input; } public Task Run(CancellationToken cancellationToken, BlockingCollection<Stream> input) { return Task.Factory.StartNew(() => { foreach (Stream stream in input.GetConsumingEnumerable(cancellationToken)) { WriteToDisk(stream); } // Should I call WriteRemaining here or should I have // a process running after this task exited which // will call WriteRemaining WriteRemaining(); }); } public void WriteRemaining() { foreach (Stream stream in input) { WriteToDisk(stream); } } } 

I know this is a slightly open question, the application / requirements / number of files to write also play a role, but I'm looking for general recommendations / best practices here.

+8
c # task-parallel-library task
source share
1 answer

Cancel is a joint action when working with a parallel task library, and yes, it is recommended that you cancel the cancel.

Remember that this is cancellation, not cancellation and deletion. If you have additional operations that need to be performed as a result of the cancellation, then these operations must be performed outside the original task that was canceled.

Note that this will not stop you from calling ContinueWith and performing the operation in the new Task , which checks whether the IsCanceled property IsCanceled true , and then performs a cleanup based on this.

The key point here is that you do not want to block the original Task that has been canceled, but you can start a new Task to perform any cleanup you need as a result of the cancellation.

+9
source share

All Articles