Threaded Cross-Class Winform Manipulation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • i

    Threaded Cross-Class Winform Manipulation

    Hi,

    I'm trying to get a seperate class, initialized by a form class, to
    manipulate certain objects on the form (ex: add to a listbox). The
    manipulation will occur via a thread that is not the normal WinForm GUI
    thread. How would I go about doing this?

    I have this code for cross-thread WinForm manipulation, but only from within
    the WinForm class:

    public delegate void LogDelegate(str ing txt);

    public void Log(string txt)
    {
    if (InvokeRequired )
    {
    Invoke(new LogDelegate(Log ), txt);
    return;
    }

    lstLog.Items.In sert(0, DateTime.Now.To String("T") + " - " + txt);
    }

    Thanks,
    Ian


  • Jon Skeet [C# MVP]

    #2
    Re: Threaded Cross-Class Winform Manipulation

    i <typppo@gmail.c om> wrote:[color=blue]
    > I'm trying to get a seperate class, initialized by a form class, to
    > manipulate certain objects on the form (ex: add to a listbox). The
    > manipulation will occur via a thread that is not the normal WinForm GUI
    > thread. How would I go about doing this?
    >
    > I have this code for cross-thread WinForm manipulation, but only from within
    > the WinForm class:
    >
    > public delegate void LogDelegate(str ing txt);
    >
    > public void Log(string txt)
    > {
    > if (InvokeRequired )
    > {
    > Invoke(new LogDelegate(Log ), txt);
    > return;
    > }
    >
    > lstLog.Items.In sert(0, DateTime.Now.To String("T") + " - " + txt);
    > }[/color]

    You'd do it in exactly the same way as the above, but using form.Invoke
    and form.ListLog or however you want to expose the ListBox to other
    classes. Of course, you could make sure that the only thing which has
    access to the controls is the form class itself, and just give
    thread-safe ways of performing certain operations (as you have above).
    Personally, I think that's generally preferable to letting other
    objects manipulate the UI, but it depends on the situation.

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    Working...