c pound

I reject your reality and substitute my own!
posts - 46, comments - 37, trackbacks - 40

My Links

News

Archives

Image Galleries

Blog Communities

Blog is a stupid word

Lunch Hour

Resources

Thursday, January 05, 2006

Arcane Asynchronous Invocation

Say you want to call a method on a control on your form from a thread... For example, you might want to populate a ListBox with a lot of data or with data from a really slow data source. In these cases you'll probably be using a seperate thread to get the data because it's generally a Bad Idea to block (freeze) your UI while you wait for all the data to come in. Especially if the data is of an indeterminate length. So, one way to get at that ListBox from a seperate thread it is to use Control.Invoke:

private void StartAsynchLoad()
{
    this.lstDatabases.Items.Clear();
    //load the databases asynchronously
    Thread t = new Thread(new ThreadStart(LoadDatabasesThread));
    t.Start();
}

private
void LoadDatabasesThread()
{
    //load the databases into the listbox
    string dataSource = this.txtServer.Text;
    string [] names = DataAccess.Instance.GetDatabases(dataSource);
    foreach(string name in names)
    {
        this.Invoke(new AddItemDelegate(AddItem), new object[]{name});
    }
}

private
delegate void AddItemDelegate(string text);
private void AddItem(string text)
{
    this.lstDatabases.Items.Add(text);
}

posted @ Thursday, January 05, 2006 1:12 PM | Feedback (0) |

The way things are done

So, what if you need to pop up a dialog box that could potentially abort the application before you pop up your main form? There are usually no good reasons to construct objects that you don't intend to use. That would include opening a Form which will immediately be closed. But is the following acceptable? I know it's possible... I'm doing it. But what could go wrong in this situation? This must be bad in some way that I haven't found yet.

[STAThread]
static void Main()
{
    //let the user choose a database before we start the program
    DialogResult dr = frmDatabases.Instance.ShowDialog();

    if
(dr == DialogResult.OK)
        Application.Run(
new frmMain());
}

posted @ Thursday, January 05, 2006 6:43 AM | Feedback (1) |

Powered by: