# Inducing a Task to finish

**URL:** <https://discourse.julialang.org/t/inducing-a-task-to-finish/53923>\
**Category:** General Usage\
**Created:** [January 25, 2021, 6:37pm UTC](https://discourse.julialang.org/t/inducing-a-task-to-finish/53923 "2021-01-25T18:37:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Josiah\_Slack](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/josiah_slack/32/8319_2.png) [@Josiah\_Slack](https://discourse.julialang.org/u/Josiah_Slack)\
**Post date:** [January 25, 2021, 6:37pm UTC](https://discourse.julialang.org/t/inducing-a-task-to-finish/53923/1 "2021-01-25T18:37:03Z")

</div>

I’m afraid there a lot of moving parts in this question. I’ve created a Task that reads from a Channel and writes to a WebSocket. I’d like to be able to `wait()` for the Task to finish, and I’d like the Task to finish when the WebSocket has been closed by the client at its other end. Here’s what the function looks like:

```julia
function listener(port::Int64, channel::Channel)
    HTTP.listen(Sockets.localhost, port) do http::HTTP.Stream
        if HTTP.WebSockets.is_upgrade(http.message)
            HTTP.WebSockets.upgrade(http, binary=true) do ws
                try
                    while !eof(ws)
                        _ = readavailable(ws)
                        bytes = take!(channel)
                        write(ws, bytes)
                    end
                catch err
                    if isa(err, InvalidStateException)
                        @info "Channel for $port is closed, exiting"
                    end
                end
            end
        end
    end
end

```

One thing I’ve tried that is partly successful (but pretty ugly), is to call `throwto(task, InterruptException())`. Among the many things I don’t like about that approach is that `listener()` isn’t directly responding to its websocket being closed.
