问题描述
我有一个从 GUI 产生的工作线程(用于 GUI 性能),我如何访问 GUI,例如从线程本身产生新的窗口/小部件?
I have a worker thread spawned from a GUI (for GUI performance), how do I access GUI, such as spawning new windows/widgets from the thread itself?
我尝试使用委托,但它似乎不起作用.有任何想法吗?可能的例子?谢谢.
I tried using delegates but it doesn't seem to be working. Any ideas? Possibly examples? Thank you.
推荐答案
根据他们的最佳实践:
Gtk# 不是一个线程安全的工具包,这意味着一次只有一个线程可以安全地调用 Gtk# 上的方法.该线程通常是执行主循环的线程(此时控制已显式转移到 Gtk).
Gtk# is not a thread-safe toolkit, which means that only one thread at a time can safely invoke methods on Gtk#. This thread is typically the thread executing the main loop (which is when control has been explicitly transfered to Gtk).
当应用程序开发人员需要让线程更新图形用户界面的某些元素时,他们必须获得一个允许他们发出 Gtk# 工具包调用的锁,或者他们可以让他们的代码在与执行 Gtk# 工具包的线程相同的线程上执行.执行主循环.
When application developers need to have threads update some element of the graphical user interface they have to either acquire a lock that allows them to issue Gtk# toolkit invocations or they can make their code execute on the same thread as the one thread that executes the main loop.
要在 GTK+ 主循环线程上调用方法并避免 GTK 出现任何线程问题,您可以使用 Gtk.Application.Invoke() 方法(如果您的目标是 Gtk# 1.0,您可以使用 Gtk.ThreadNotify).
To invoke a method on the GTK+ main loop thread and avoid any threading problems with GTK, you can use the Gtk.Application.Invoke() method (if you are targetting Gtk# 1.0 you can use Gtk.ThreadNotify).
提供以下示例;您应该使用 Invoke
从主循环中执行任何 Gtk 代码:
The following example is provided; you should use Invoke
to execute any Gtk code from within the main loop:
public void ThreadedMethod()
{
Gtk.Application.Invoke(delegate {
do_stuff_in_main_thread();
});
}
这篇关于如何从多线程访问 GUI (GTK)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!