uasyncio task cancellation with confirmation

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

uasyncio task cancellation with confirmation

Post by pythoncoder » Thu Jan 11, 2018 9:45 am

The uasyncio library V1.7.1 on PyPi now supports task cancellation by means of cancel(coro). This is essential in many applications, and as far as I was concerned was the last missing feature of the library.

It does not provide a means of pausing until cancellation is complete. This is a common requirement. It can be achieved with exception trapping and the use of synchronisation primitives but I thought it worth offering a little syntactic sugar to hide these gory details which are not entirely free from potential bear-traps ;) My asyn library now does this. A typical use-case is as follows:

Code: Select all

import asyn
async def comms():  # Perform some communications task
    while True:
        await initialise_link()
        try:
            await do_communications()  # Launches Cancellable tasks
        except CommsError:
            await asyn.Cancellable.cancel_all()
        # All sub-tasks are now known to be stopped. They can be re-started
        # with known initial state on next pass.
For anyone already using my efforts please accept my apologies for the twists and turns in the API. It's taken me a while to arrive at a (hopefully) neat and easily used solution. There is now an @cancellable decorator which can obviate the need for explicit exception trapping.
Peter Hinch
Index to my micropython libraries.

Post Reply