我尝试运行以下代码,但是 wait_for_connection()
似乎在前两行之前运行,我似乎不明白为什么?我真的需要在 wait_for_connection()
之前运行前两行函数被调用。即使我输入 sleep(1)
在调用 wait_for_connection()
之前函数,它仍然在前面的行之前运行。
我的代码如下:
void wait_for_connection() {
for (int i = 0; i < 10; i++) {
g_print("Checking server...\n");
if (connected == 1) {
g_print("Connected to: %s", selectedServerStr);
break;
}
sleep(1);
}
}
int connect_server(GtkButton *button, gpointer user_data) {
.......
if (gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selectedServer), &model, &iter)) {
path = gtk_tree_model_get_path(model, &iter);
serverIndex = *gtk_tree_path_get_indices(path);
g_print("Selected Server IP: %s\n", serverIPArray[serverIndex][0]);
gtk_widget_set_sensitive(serverList, FALSE); // These 2 lines needs to be run first
append_to_log("Attemping connection, please wait...", 1);
wait_for_connection(); // This is where the error lies, this runs before the above 2 lines
return 1;
} else {
gtk_widget_set_name(serverBox, "fieldsError");
g_print("No server selected: Aborting...\n");
return -1;
}
}
行
gtk_widget_set_sensitive()
用于禁用选择小部件的用户交互,但是这似乎直到 wait_for_connection()
之后才会发生功能已完成打印“检查服务器...” 10 次。值 connected
为 0,所以目前该功能只打印“检查服务器...”10 次。有人对可能发生的事情有任何想法吗?任何帮助将不胜感激,谢谢。
最佳答案
几乎所有平台上的 GUI 应用程序都是事件驱动的。他们需要他们的事件处理函数定期执行,否则用户界面将看起来没有响应,甚至看起来像是被锁定或什么都没有发生。
在您的 wait_for_connection
你有一个循环最多可以迭代十次,每次迭代你都会做sleep(1)
它睡了一整秒钟。虽然此循环正在迭代和休眠,但不会发生事件处理,并且如上所述,这会使您的用户界面看起来像没有响应并且不做任何事情。
您还需要将代码修改为事件驱动的,因此“连接”状态将作为您可以处理的事件发送,或者以某种方式使轮询异步,使其与事件处理并行发生。
关于C - 语句未按顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61311468/