Syncronizing actions in Silverlight

早过忘川 提交于 2019-12-22 04:18:13

问题


I have a Silverlight app that uses actions to get data from the model (which again gets the data from WCF services).

I need to somehow sync 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 I can use a counter to keep track of how many has returned, but is there not a better way to do this?

EDIT: user24601 has a good answer, but CountdownEvent does not exist in silverlight, any other great ideas? :)


回答1:


Yes, a counter is what you need. The '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();
}



回答2:


Solved the problem my self, 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();
        }
    }
}

usage:

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;
}


来源:https://stackoverflow.com/questions/8879870/syncronizing-actions-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!