0

I evaluate JavaScript in my Qt application using QScriptEngine::evaluate(QString code). Let's say I evaluate a buggy piece of JavaScript which loops forever (or takes too long to wait for the result). How can I abort such an execution?

I want to control an evaluation via two buttons Run and Abort in a GUI. (But only one execution is allowed at a time.)

I thought of running the script via QtConcurrent::run, keeping the QFuture and calling cancel() when the Abort is was pressed. But the documentation says that I can't abort such executions. It seems like QFuture only cancels after the current item in the job has been processed, i.e. when reducing or filtering a collection. But for QtConcurrent::run this means that I can't use the future to abort its execution.

The other possibility I came up with was using a QThread and calling quit(), but there I have a similar problems: It only cancels the thread if / as soon as it is waiting in an event loop. But since my execution is a single function call, this is no option either.

QThread also has terminate(), but the documentation makes me worry a bit. Although my code itself doesn't involve mutexes, maybe QScriptEngine::evaluate does behind the scenes?

Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

Is there another option I am missing, maybe some asynchronous evaluation feature?

4

2 回答 2

0

虽然并发任务本身不能“从外部”中止,但QScriptEngine可以告诉(当然是从另一个线程,如您的 GUI 线程)中止执行:

QScriptEngine::abortEvaluation(const QScriptValue & result = QScriptValue())

可选参数用作传递给调用者的“伪结果” evaluate()

您应该在某处设置标志或使用特殊结果值,abortEvaluation()以使调用程序例程能够检测到执行已中止。

注意:使用isEvaluating()您可以查看当前是否正在运行评估。

于 2013-03-29T22:31:45.210 回答