Max T Max T - 7 months ago 58
C# Question

C# - How to react on an Event raised in another class?

I've Got 2 classes:

One Service which creates a FileSystemWatcher that fires an event when the watched File is saved by Word.
And one UserControl that has got some functions I need to execute when the SaveEvent is fired.

How can I react to the SaveEvent in the UserControl?


I would create an event in the Service which will be raised when the FileSystemWatcher is raised. The Service should wrap the FileSystemWatcher. The parent of both objects will call a method on the UserControl.

For example: (PSEUDO)

class MyProgram
    Service svc;
    UserControl ctrl;

    public MyProgram()
        // create the control
        ctrl = new UserControl();

        // create the service
        svc = new Service();
        svc.SaveEvent += FileChanges;

        /////// you might construct something like:   _(do not use both)_
        svc.SaveEvent += (s, e) => ctrl.FileIsSaved(e.Filename);

    private void FileChanges(object sender, ServiceFileChangedEventArgs e)

class Service
    // FileSystemWatcher
    private FileSystemWatcher _watcher;

    public Service() // constructor
        // construct it.
        _watcher = new FileSystemWatcher();
        _watcher.Changed += Watcher_Changed;

    // when the file system watcher raises an event, you could pass it thru or construct a new one, whatever you need to pass to the parent object
    private void Watcher_Changed(object source, FileSystemEventArgs e)
        SaveEvent?.Invoke(this, new ServiceFileChangedEventArgs(e.FullPath)); // whatever

    public event EventHandler<SaveEventEventArgs> SaveEvent;

class SaveEventEventArgs : EventArgs
    // filename etc....

This is just some pseudo example code. But the important thing is, Your Program/Usercontrol should NOT depend on the FileSystemWatcher. Your Service should wrap it. So whenever you decide to change the FileSystemWatcher to (for example) a DropBoxWatcher, the rest of the program isn't broken.