views:

30

answers:

2

Hey-

I have a GUI class and a database class. I do something like:

Dim db as Database = getDatabaseObject(logTxtBox)
db.executeNonQuery("some update command here")

Within executeNonQuery I connect to the db, execute the command, disconnect and catch the exceptions. logTxtBox is the GUI txt box I want log messages written to. Currently it writes something like:

Connected to DB successfully
Executing "some update command here"
Excepetion: ........
Disconnecting from DB

I feel like this isn't the best structure for my logging. As soon I kick off executeNonQuery with a BackgroundWorker instead of with the main GUI thread I cannot access the GUI's logTxtBox from the BackgroundWorker's thread.

Is there a better way to implement this kind of functionality?

Thanks-

Jonathan

A: 

To use a UI component from a background thread make sure you use Control.Invoke() to make sure the code runs in the UI thread.

Here's some C# code that calls a method on the UI thread and passes in a parameter:

    this.Invoke(new Action<string>(MyMethod), "something to log");

    private void MyMethod(string logData) {
        // set some text here
    }
Eilon
A: 

You could raise events in within your database class an handle those events in the ui. For example you could create a custom "StatusChanged" event and pass the current state within the eventargs.

Andre Kraemer