views:

30

answers:

1

I've got a winforms application that is set up in the following manner: 2 buttons, a textbox, an class object MX with a collection K as its member, function X and another function, Y.

  1. Function X parses a large database and enumerates some of its data in collection K.
  2. Button 1 calls function X.
  3. Function Y walks through the above collection and prints out the data in the textbox.
  4. Button 2 calls function Y.

I'd like to call function X through a worker thread in such a way that:

  1. The form remains responsive to user input. This comes intrinsically from the use of a separate thread.
  2. There is never more than a single instance of function X running at any point in time.
  3. MX/K can be accessed by both functions at all times.

What would be the most efficient implementation of the above environment ?

+1  A: 

When you press button 1, you can call X using BackgroundWorker to run it in a separate thread. Then set a variable (or grey out Button 1) such that the user cannot run X again.

X can write to its own collection while it processes the DB. Then it can replace an instance variable with this collection. By only doing a single replacement you can avoid synchronization problems between X and the UI thread.

After X completes, you can use a BackgroundWorker event to let the UI know the operation is complete. Then you reset the same variable (or ungrey the button) to let the user know they can now run X again - if necessary.

What do you think? Does that help at all?

Justin Ethier