http://qs321.pair.com?node_id=11115289

IB2017 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am creating an updater for my Tk program on Windows. It simply needs to download an installer and run it. The download part is done by the following subrutine which also updates a progress bar. Is there an easy way to break out of the download (possibily without to rewrite the whole program using threads etc.).

sub doUpdate{ print "doUpdate\n"; my $url = 'https://www.domain.com/download/updater.exe'; my $file = $Path . '/updater.exe'; print "Saving updater in $file\n"; my $ttlDown = 0; my $ua = LWP::UserAgent->new; open my $out, '>:raw', $file or die "$file: $!"; my $resp = $ua->get( $url, ':content_cb' => sub { my ($data, $response) = @_; my $size = $response->content_length; $ttlDown += length $data; $percent_done= $ttlDown * 100.0 / $size; print {$out} $data; $mw->update(); }, ); close $out; print "Out\n"; }

Replies are listed 'Best First'.
Re: Break out from download
by kcott (Archbishop) on Apr 09, 2020 at 19:49 UTC

    G'day IB2017,

    "Is there an easy way to break out of the download"

    Take a look at the last paragraph of "LWP::UserAgent: get" which has:

    "The callback can abort the request by invoking die()."

    — Ken

      Hi Ken

      I do not quite get it: invoking die() as for killing my script (main program). I can't find any object method called die in LWP.

        LWP invokes the callback inside an eval; using die will be caught and translated into an "X-Died" header in the response object.

        You will need to arrange for the "Cancel" button to set a flag that the callback then checks. Having the Tk callback handler directly die will abort the run through the event loop and may or may not cause problems. Tk is a very complex XS module, so it would be best to avoid throwing an exception "around the event loop" directly.

        The die can be caught with an eval and will not necessarily always cause perl to exit.

        (But POSIX has _exit if you ever did need to stop a process immediately</extrememly-tangentially-related-aside>).

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

        invoking die() as for killing my script (main program)

        does it, tho? maybe try first, worry later?