revolutionkpi
revolutionkpi

Reputation: 2682

Asynchronous event in c#

In my application I have three asynchronous events.

After all of them are complete I need to call some Method1().

How can I implement this logic?

Update

Here is one of my asynchronous events:

 public static void SetBackground(string moduleName, Grid LayoutRoot)
        {
            var feedsModule = FeedHandler.GetInstance().ModulesSetting.Where(type => type.ModuleType == moduleName).FirstOrDefault();
            if (feedsModule != null)
            {
                var imageResources = feedsModule.getResources().getImageResource("Background") ??
                                     FeedHandler.GetInstance().MainApp.getResources().getImageResource("Background");

                if (imageResources != null)
                {

                    //DownLoad Image
                    Action<BitmapImage> onDownloaded = bi => LayoutRoot.Background = new ImageBrush() { ImageSource = bi, Stretch = Stretch.Fill };
                    CacheImageFile.GetInstance().DownloadImageFromWeb(new Uri(imageResources.getValue()), onDownloaded);
                }
            }
        }

Upvotes: 1

Views: 152

Answers (3)

Jon
Jon

Reputation: 2891

You should use WaitHandles for this. Here is a quick example, but it should give you the basic idea:

    List<ManualResetEvent> waitList = new List<ManualResetEvent>() { new ManualResetEvent(false), new ManualResetEvent(false) };

    void asyncfunc1()
    {
        //do work
        waitList[0].Set();
    }
    void asyncfunc2()
    {
        //do work
        waitList[1].Set();
    }

    void waitFunc()
    {
        //in non-phone apps you would wait like this:
        //WaitHandle.WaitAll(waitList.ToArray());
        //but on the phone 'Waitall' doesn't exist so you have to write your own:
        MyWaitAll(waitList.ToArray());

    }
    void MyWaitAll(WaitHandle[] waitHandleArray)
    {
        foreach (WaitHandle wh in waitHandleArray)
        {
            wh.WaitOne();
        }
    }

Upvotes: 0

Mene
Mene

Reputation: 3799

Not given any other information, what will work is to use a counter. Just an int variable that is initialized to be 3, decremented in all handlers and checked for equality to 0 and that case go on.

Upvotes: 1

John3136
John3136

Reputation: 29266

Bit field (or 3 booleans) set by each event handler. Each event handler checks that the condition is met then calls Method1()

tryMethod1()
{
   if (calledEvent1 && calledEvent2 && calledEvent3) {
       Method1();
       calledEvent1 = false;
       calledEvent2 = false;
       calledEvent3 = false;
   }
}


eventHandler1() {
    calledEvent1 = true; 
    // do stuff
    tryMethod1();
}

Upvotes: 2

Related Questions