更改Gtk.Label.Text并不总是有效 [英] Changing Gtk.Label.Text does not always work
问题描述
我有一个Gtk.Menu和4个MenuItems。以下代码每秒执行一次,以更改每个MenuItem的Label.Text:
double d = new Random()。NextDouble (); ((标签)((MenuItem)menu.Children [i])Child($ i
)(int i = 0; i <4; i ++) Text = d.ToString();
}
我使用单声道2.10.8.1和monodevelop 3.0.3.2 ubuntu linux。
问题 我的快速入侵 我可以通过让线程在每个循环中休眠1 ms来解决这个问题: 问题
$ b 问题是并非所有的标签都会更新(有时只是第一个和第二个,有时只是第一个和最后一个)。
< ((标签)((MenuItem)menu.Children [i])。Child).Text = d($)的ToString();
Thread.Sleep(1); // HACK !!!
}
ol>
原因是您正在更新主GTK之外的 GUI 线程。
$ b 当您调用 Gtk.Application时,拥有事件循环的主要GTK线程 .run 。
有几种方法可用于更新,您可以尝试 Gtk.Application.Invoke ,
Gtk.Application.Invoke(delegate {
double d = new Random()。NextDouble();
(for i = 0; i <4; i ++){
((Label)((MenuItem)menu.Children [i])。Child).Text = d.ToString();
}
});
这个链接可能是有趣的。
I have a Gtk.Menu with 4 MenuItems. The following code is executed every second to change the Label.Text of each MenuItem:
double d = new Random().NextDouble();
for (int i = 0; i < 4; i++)
{
((Label)((MenuItem)menu.Children[i]).Child).Text = d.ToString();
}
I am using mono 2.10.8.1 with monodevelop 3.0.3.2 on ubuntu linux.
the issue
The problem is that not all Labels are getting updated (sometimes only the first and the second, sometimes only the first and the last).
my quick hack
I can overcome this issue by letting the thread sleep for 1 ms in each loop:
for (int i = 0; i < 4; i++)
{
((Label)((MenuItem)menu.Children[i]).Child).Text = d.ToString();
Thread.Sleep(1); // HACK !!!
}
questions
- What is the reason for this issue?
- What would be a better solution?
The reason for this is that you are updating the GUI fron outside of the main GTK thread.
The main GTK thread, who owns the event loop, is created when you call Gtk.Application.run .
Several methods are avalaible for updating, you could try Gtk.Application.Invoke,
Gtk.Application.Invoke (delegate {
double d = new Random().NextDouble();
for (int i = 0; i < 4; i++) {
((Label)((MenuItem)menu.Children[i]).Child).Text = d.ToString();
}
});
This link could be of interest.
这篇关于更改Gtk.Label.Text并不总是有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!