我们如何在tcl tkcon GUI中停止执行函数?

时间:2017-10-26 16:18:30

标签: tcl

我想在TkCon GUI中动态停止函数执行。例如,我在TkCon GUI上执行命令和过程,如果我想在运行中停止它,我们怎么能这样做?在linux控制台中我们使用“ctrl + C”。这在TkCon GUI中不起作用。

1 个答案:

答案 0 :(得分:0)

通常情况下,你不能。问题是您运行的代码与运行GUI的代码位于同一个线程中,因此程序不会响应您要求它停止。 (另外 Ctrl + C 通常用于其他目的,例如复制到剪贴板。)

但是,如果您在一个单独的线程中运行程序并保留该线程的句柄,您可以cancel the execution(假设您有Tcl 8.6)。在它最简单的形式中,你这样做:

thread::cancel $threadID

这将解除执行,直到代码catch被强制插入的错误。(假设代码没有像外部IO调用那样停止。)您可能还需要指定{ {1}}选项如果捕获嵌套正在重新启动循环;在展开时,线程将返回到明确定义的状态。

-unwind

默认情况下,TkCon GUI不会为您提供此功能。利用这个的最简单方法是在一个小的主执行上下文中运行你的代码,如下所示:

thread::cancel -unwind $threadID

您可能还需要设置后台错误处理程序。

我用以下方法测试了上述内容:

package require Thread

set app_runner [thread::create { thread::wait }]
proc app_eval {args} {
    global app_runner
    thread::send -async $app_runner [concat {*}$args] app_result
}
# Simple receiver for async returns
trace add variable app_result write {apply {args {
    global app_result
    if {$app_result ne ""} {
        puts $app_result
    }
}}}
proc app_cancel {} {
    global app_runner
    thread::cancel $app_runner
}
# Bring the stack trace locally
proc app_handle_error {- info} {
    puts stderr $info
}
thread::errorproc app_handle_error

它工作得很好。将这些操作绑定到GUI中只是一个练习。