onCleanup order of execution
Show older comments
When onCleanup objects are created in a function, they execute their cleanup routines when destroyed. If several onCleanup objects are created in a function, they will all execute their cleanup routines. I have 2 questions about the order of execution:
- Say 2 onCleanup objects are created, in this order: objCleanup1 and objCleanup2. The function they are created in then completes, and the objects are destroyed. I assume that their corresponding cleanup routines will execute in arbitrary order (or at least not necessarily in the order of creation). Is this correct?
- Say both cleanup routines are very long (i.e., several seconds). Can we safely assume that as long as a single cleanup routine is running, the next one will not start (even if their order is, in fact, arbitrary)?
Thank you in advance.
Accepted Answer
More Answers (1)
Jacob Lynch August
on 27 Sep 2018
Edited: Jacob Lynch August
on 27 Sep 2018
onCleanup objects can be stored in a cellular vector, and will be performed first to last. You should know the number of total tasks, and the order they should be run. Usually my code requires a first-in-last-out ordering. I would setup the onCleanup tasks like this:
ON_CLEANUP_TASKS = cell(N,1);
ON_CLEANUP_TASKS{N} = onCleanup(@()TaskN);
% ... some operations and additional tasks
ON_CLEANUP_TASKS{1} = onCleanup(@()Task1);
Even though TaskN was created first, it will be done last.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!