Sync Actions in Silverlight

I have a Silverlight application that uses actions to retrieve data from a model (which again retrieves data from WCF services).

I need to somehow synchronize two ActionCallbacks or wait for them, and then execute some code.

Example:

_model.GetMyTypeList(list => { MyTypeList.AddRange(list); }); _model.GetStigTypeList(list => { StigTypeList.AddRange(list); }); doSomethingWhenBothHaveReturned(); 

I know that I can use the counter to track how much has returned, but is there a better way to do this?

EDIT: user24601 has a good answer, but CountdownEvent doesn't exist in silverlight, any other great ideas? :)

+8
c # delegates action
source share
2 answers

I solved the problem myself using a counter:

 public class ActionWaitHandler { private int _count; private readonly Action _callback; public ActionWaitHandler(int count, Action callback) { _count = count; _callback = callback; } public void Signal() { _count--; if (_count == 0) { _callback(); } } } 

using:

 public void method() { var handler = new ActionWaitHandler(2, OnActionsComplete); _model.GetMyTypeList(list => { MyTypeList.AddRange(list); handler .Signal(); }); _model.GetStigTypeList(list => { StigTypeList.AddRange(list); handler .Signal(); }); } public void OnActionsComplete() { dosomething; } 
+4
source share

Yes, a counter is what you need. A more elegant solution would be to use a countdown event:

 using (CountDownEvent countDownEvent = new CountDownEvent(2)) { _model.GetMyTypeList(list => { MyTypeList.AddRange(list); countDownEvent.Signal(); }); _model.GetStigTypeList(list => { StigTypeList.AddRange(list); countDownEvent.Signal(); }); countdownEvent.Wait(); doSomethingNowThatWereComplete(); } 
+9
source share

All Articles