开发者

Callback event subscription

开发者 https://www.devze.com 2023-03-23 04:36 出处:网络
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. Inst

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 fir开发者_如何转开发ed.

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


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.


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!");
  }
}


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.");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消