2012-08-02 85 views
1

在我的應用程序中,我有三個異步事件。c中的異步事件#

所有這些都完成後,我需要調用一些Method1()。

我該如何實現這個邏輯?

更新

這裏是我的異步事件之一:每個事件處理程序中設置

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

哪裏是事件?在每一個事件我從網上 – nawfal 2012-08-02 08:03:05

+0

,它會更容易講一個解決方案 – revolutionkpi 2012-08-02 08:03:42

+0

一些數據,如果u顯示我們律」你的代碼位 – nawfal 2012-08-02 08:04:38

回答

2

位字段(或3布爾值)。每個事件處理程序檢查的條件得到滿足,然後調用方法1()

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


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

不因任何其他信息,什麼工作是使用計數器。只是一個初始化爲3的int變量,在所有處理程序中遞減,並檢查相等爲0,並且該情況繼續。

+0

一件事:如果你的事件在不同的線程解僱你需要的事件處理器同步。 – Mene 2012-08-02 08:09:51

+0

我應該如何同步事件處理程序? – revolutionkpi 2012-08-02 08:13:02

+0

使用互斥鎖,或在c#中使用'lock'在所有3個處理程序中使用相同的引用。 – Mene 2012-08-02 08:14:36

0

你應該爲此使用WaitHandles。這是一個簡單的例子,但它應該給你的基本思路:

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