Changing Gtk.Label.Text does not always work

谁都会走 提交于 2019-12-10 22:39:31

问题


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

  1. What is the reason for this issue?
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!