我正在尝试学习Vala,所以我正在制作一个小型GUI应用程序。我以前的主要语言是C#所以事情进展顺利。
然而,我现在已经碰壁了。我需要连接到外部网络服务器(使用GIO),它不能立即回复我的客户端。这使得GUI在程序连接并执行其操作时冻结。
在C#中,我可能会在这种情况下使用BackgroundWorker。我似乎无法为Vala找到类似的东西。
基本上,我有一个MainWindow.vala,我已经连接了一个信号,用于点击某个按钮来创建一个新的ProcessingDialog.vala实例的方法。这显示了MainWindow上的一个对话框,我希望用户在程序执行工作时看到它(连接到服务器,进行通信)。
有哪些方法可以让这种情况发挥作用?
答案 0 :(得分:3)
GIO提供异步方法,请参阅异步客户端,例如:https://live.gnome.org/Vala/GIONetworkingSample
如果您不了解Vala中的异步方法,请尝试查看教程:https://live.gnome.org/Vala/Tutorial#Asynchronous_Methods
答案 1 :(得分:0)
lethalman上面的答案可能最有意义,如果你正在进行网络通话,异步请求确实是你最好的选择。在其他情况下,您可以使用Vala内置的thread support来完成后台任务。看起来很快,将会有一个更好的库,但这是稳定的。
// Create the function to perform the task
public void thread_function() {
stdout.printf("I am doing something!\n");
}
public int main( string[] args ) {
// Create the thread to start that function
unowned Thread<void*> my_thread = Thread.create<void*>(thread_function, true);
// Some time toward the end of your application, reclaim the thread
my_thread.join();
return 1;
}
请记住使用“--thread”选项进行编译。