user1231231412
user1231231412

Reputation: 1659

Callback event subscription

I have a WorkManager class with a AddWork() method and a WorkDone event. Other components of the system will call WorkManager.AddWork() and should only be notified when their work has completed. Instead of the event notifying every client when every event fires.

I'm struggling to find an elegant solution.

Thanks all!

EDIT: Another way to look at this is, say I have a class called JobManager with an event called OnWorkDone(). I have 2 other classes that need to listen to this event.

Event subscriber class 1

WorkManager.OnWorkDone += WorkDoneJob1;
void WorkDoneJob1()
{
     print("Job 1 is done!");
}

Event subscriber class 2

WorkManager.OnWorkDone += WorkDoneJob2;
void WorkDoneJob2()
{
     print("Job 2 is done!");
}

In this model if the jobmanager completes job1 it will print "job 1 done" and "job 2 done" since all clients get notified that event fired.

I only want class1 to get a notification when it's job has completed.

Upvotes: 0

Views: 1998

Answers (3)

Jimmy Hoffa
Jimmy Hoffa

Reputation: 5967

Put the event on the job object you add to the manager and subscribe to it before you AddWork() it to the manager. Alternatively make the manager accept a callback with the addwork method and have a dictionary of jobs and callbacks which the manager fires when the jobs done.

Upvotes: 1

Hand-E-Food
Hand-E-Food

Reputation: 12814

Don't use events. Just call the class's Complete method.

I don't usually write C# so my syntax may be out.

class WorkManager {
    void DoWord {
        WorkTask task = GetNextWorkTask();
        PerformWork(task);
        task.Complete();
    }

    WorkTask GetNextWorkTask() { ... }

    void PerformWork(WorkTask task) { ... }
}

virtual class WorkTask {
    virtual void Complete;
}

class WorkTask1 : WorkTask {
    void Complete {
        print("Job 1 done.");
    }
}

Upvotes: 0

benPearce
benPearce

Reputation: 38343

Change your OnWorkDone delegate to include an event args type, which could include an identifier for the job completed, then your handler can check if it cares about the event or not.

public delegate void OnWorkDone(object jobIdentifer);

void WorkDoneJob1(object jobIdentifer)
{
  if (jobIdentifer == this.jobIdentifer)
  {
     print("Job 1 is done!");
  }
}

Upvotes: 0

Related Questions