I can think of a variety of reasons where you don't want to bother with the
tasks (possibly because they might resist being cancelled) but you still
want to close the loop. In your finally clause you should be able to write
something like this:

for t in asyncio.Task.all_tasks(loop):
    t.cancel()
loop.run_until_complete(asyncio.sleep(0.1))  # Give them a little time to
recover
loop.close()

Exactly how long you want to give the tasks to handle their cancellation is
one of the design decisions that make it difficult to do this automatically
in loop.close() -- but if you don't run the loop at all there is not much
of a point in cancelling the tasks (as the cancelled task won't run to
process the exception thrown into it until the loop schedules it).

On Mon, Sep 8, 2014 at 1:15 AM, Martin Teichmann <[email protected]
> wrote:

> Hi List,
>
> I use asyncio to start several tasks with asyncio.async. Several
> of them need to close some things before exiting, so I use
> a try...finally construction to do that. Unfortunately, the
> finalizers are never called.
>
> When running the event loop, I am using the same code as in
> several examples in the docs:
>
>     try:
>         loop.run_forever()
>     finally:
>         loop.close()
>
> The documentation for BaseEventLoop.close says that it "clears the queues".
> Going through the code I realized that it is doing exactly just that.
>
> I do think it should actually do more, namely it should close the running
> tasks (i.e. raise a CancelledError in the coroutines). Otherwise there is
> not
> much sense to have this close method at all, the garbage collector is good
> enough to deal with clearing queues.
>
> Now one might argue that the behavior shouldn't change anymore, but
> maybe we can add a new method, e.g. BaseEventLoop.cancel(),
> which cancels all running coroutines.
>
> Greetings
>
> Martin
>



-- 
--Guido van Rossum (python.org/~guido)

Reply via email to