문제

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?
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top