tags:

views:

105

answers:

2

I'm currently trying to separate some of my code from my main form, and create class files to handle some operations. I've read that it's not good practice to tie classes to a UI, so I was wondering how to still return information on the progression of events taking place in the class. When the code was present in the main form, I would write the status updates of the function to a text box, so that the user could know what was occurring.

How would I go about updating the user on a routine's status from a class via the main form?

+8  A: 
class Foo
{
    public event EventHandler DidSomething = delegate { };

    public void DoSomething( )
    {
        // do stuff, fire event
        OnDidSomething( EventArgs.Empty );
    }

    protected virtual void OnDidSomething( EventArgs e )
    {
        DidSomething( this, e );
    }
}

The main form can subscribe to the "DidSomething" event and take action as needed.

public class Form1 : Form
{ 
    public Form1( )
    {
        Foo f = new Foo( )
        f.DidSomething += f_DidSomething;
        f.DoSomething( );
    }


    void f_DidSomething( object sender, EventArgs e )
    {
        MessageBox.Show( "Event Fired" );
    }
}
Ed Swangren
A: 

You could define a "StatusChanged" event on your worker class. Then the UI class can register for that event and take whatever action is needed to inform the user.

David