问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/19738488/changing-gtk-label-text-does-not-always-work