C# Developers' Journal (original) (raw)

GUI multithreading woes Pt. 2 Alright experts...I need your help again. Thanks again for the help before.

I have a listbox on the main form called outputList. In the main form's code I have the following:

    public delegate void AddTextDelegate(string text);

    public void AddText(string text)
    {
        if (outputList.InvokeRequired) {
            AddTextDelegate del = new AddTextDelegate(AddText);
            Invoke(del, new object[] { text });
        } else {
            outputList.Items.Add("[" + DateTime.Now + "]  " + text);

        }
    }

What I've been doing is passing a reference of the main form to the worker thread(s). It feels dirty and I don't like it, even though it works. NOTE: the worker thread is in a separate .CS file but the same namespace. I was thinking that I could just pass the delegate method above so the worker thread could write to the listbox through that. The problem is I don't know how to create a method in the thread class to invoke it. If I pass a reference and declare the delegate signature it works in the thread's constructor, but I don't know how to keep it beyond that (if you need clarification on that last sentence I can provide code).

Any ideas?

Thanks.

Current Mood: frustrated