Re: Making threadsafe calls : C# 2005

Keith Hill <[email protected]> Sun, 8 Jul 2007 11:13:48 -0600
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <512BE27FB3EF0B42B619503F8ECB109B02276632@wcosmb05.cos.agilent.com>
Or if you happen to be playing around on .NET 3.5 you can do something =
like this:

public static class ControlExtentions {
    public delegate void InvokeHandler();=20

    public static void SafeInvoke(this Control control, InvokeHandler =
handler) {
        if (control.InvokeRequired) {
            control.Invoke(handler);
        }
        else {
            handler();
        }
    }
}=20

private void UpdateProgress(int percentComplete)
{
    this.SafeInvoke(() =3D>
    {
           _progressBar.Value =3D percentComplete;
    });
}

--
Keith

> -----Original Message-----
> From: Peter Ritchie
> [mailto:[email protected]]
> Sent: Tuesday, June 19, 2007 9:25 PM
> Subject: Re: Making threadsafe calls : C# 2005
>=20
> You just need to marshal it back to the UI thread via Control.Invoke =
or
> Control.BeginInvoke.  The sample just encapsulates that in a single
> method
> that first checks Control.InvokeRequired so that any thread can call
> the
> method.
>=20
> For example, on a non UI thread it's illegal to call TextBox.Text and
> to
> marshal it back to the UI thread a delegate must be created for
> Control.Invoke.
>=20
> In .NET 2.0, this can be done without explictly creating the delegate
> and
> anonymous delegates can be used:
>   public void SetText(string text)
>   {
>    if (InvokeRequired)
>    {
>     this.Invoke((MethodInvoker)delegate
>     {
>      textBox1.Text =3D text;
>     });
>    }
>    else
>    {
>     textBox1.Text =3D text;
>    }
>=20
>   }
>=20
>=20
> This way you don't have to create a delegate like SetTextCallback
> On Tue, 19 Jun 2007 21:20:48 -0400, Peter Osucha =
<[email protected]>
> wrote:
>=20
> >Thank you, Peter.
> >
> >So it seems that what I should be doing when my 'other thread' object
> raises
> >an event that is handled by one of my forms is to kick off a new
> thread
> and
> >have that thread update the necessary form controls.  Is this right?
> >

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
This list is hosted by DevelopMentor=AE  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com