Charles Demar
Charles Demar

Reputation: 41

How to I design a class so looping is not necessary?

I have to process some records. For reasons that are unnecessary to mention, I can not loop through these records at the UI layer. The client wants to be able to simply call the middle tier using a function call, have the middle tier loop through and process the records. The problem is they want the middle tier to report back a status after each record is processed. How would I design that. For what it's worth, this is c# in .net.

Upvotes: 0

Views: 100

Answers (2)

Colin
Colin

Reputation: 4135

A setup similar to this should work. It's untested/uncompiled so consider it pseudo-code. Also, it should ideally be asynchronous, but this will give you a starting point as an example of how to communicate changes back to the UI through eventing without the UI being aware of any "looping".

Event plumbing:

public class MyEventArgs : EventArgs
{
   //add properties you want to send to the UI here.
}

public delegate void ProcessedEventHandler(object sender, MyEventArgs e);

Middle tier raises events.

public class MiddleTier
{
     public event ProcessedEventHandler RecordProcessed;

     //NOTE it would be best to make a tweak to do this asynchronously
     //such that all records can be processed at the same time instead
     //of processing them sequentially. if the method were async, you
     //could do all of this without the method itself blocking.
     public void Process()
     {             
         //this loop/processing should ideally be asynchronous
         foreach(var thing in whatever)
         {
             //process thing 

             //make event args
             var args = new MyEventArgs(); //fill out properties
             //raise event
             OnProcessed(args);
         }

         private void OnProcessed(MyEventArgs args)
         {
              //follow this pattern for thread safety
              var p = RecordProcessed;
              if(p != null)
                   p(this, args);
         }
     }
}

Then in your UI layer:

//in some UI function
var mt = new MiddleTier();
//handle event
mt.RecordProcessed += 
    (s, args) =>
    {
        //update UI
    };
//kick things off
mt.Process();

Upvotes: 1

kidshaw
kidshaw

Reputation: 3451

You don't mention what technology your UI will be but assuming it is an application, you want the processing to happen on a separate thread so as to allow your UI to update.

I would look at the backgroundworker component as a starting point. It facilitates a progresschanged event you can use to notify your UI of how it getting on. Similar can be achieved using asynchronous framework.

Upvotes: 0

Related Questions