[Gtk-sharp-list] Threading problem on Windows
Michael Hutchinson
m.j.hutchinson at gmail.com
Mon Dec 1 17:26:27 EST 2008
On Mon, Dec 1, 2008 at 4:54 PM, D. Dobrev <dpldobrev at yahoo.com> wrote:
>
> Hello.
> I have the following code:
> protected virtual void OnButtonOneDieClicked(object sender, EventArgs e)
> {
> if (this.isDieRolling)
> {
> this.isDieRolling = false;
> }
> else
> {
> this.isDieRolling = true;
> Thread thread = new Thread(() =>
> {
> while (this.isDieRolling)
> {
> Thread.Sleep(1);
> Application.Invoke((image, args) =>
> {
>
> this.imageOneDie.Pixbuf = this.RollDie();
> });
> }
> });
> thread.Start();
> }
> }
>
> Its purpose is: when the button is first clicked, a few pictures (the sides
> of a die) begin rapidly changing. The second click stops the changes (this
> simulates the rolling of a die). In Linux this works perfectly, but in
> Windows the rolling rate is variable: it begins fast, then it slows down,
> then again fast, etc., with random intervals. Does anyone have an idea what
> the problem might be? If this helps, the source of my application can be
> found attached at the bottom of my
> http://www.nabble.com/forum/ViewPost.jtp?post=20758097&framed=y previous
> thread .
You don't need a thread here -- all it's giving you is semi-random
intervals of calling this.imageOneDie.Pixbuf = this.RollDie().
Thread.Sleep causes a context switch, so the thread's rate depends on
the OS' scheduler. The Application.Invoke is run on another thread
(the GTK# thread), so this also depends on the scheduler.
I recommend a GLib.Timeout: see
http://www.mono-project.com/Responsive_Applications#Timeouts and
http://www.go-mono.com/docs/monodoc.ashx?link=T%3aGLib.Timeout
It runs directly on the GTK thread at a specified rate, e.g. 30FPS
(33ms / frame):
protected virtual void OnButtonOneDieClicked(object sender, EventArgs e)
{
if (this.isDieRolling) {
this.isDieRolling = false;
} else {
this.isDieRolling = true;
GLib.Timeout.Add (33, delegate {
this.imageOneDie.Pixbuf = this.RollDie();
return this.isDieRolling;
});
}
}
There may be other factors involved, but the thread certainly isn't
doing any good.
--
Michael Hutchinson
http://mjhutchinson.com
More information about the Gtk-sharp-list
mailing list