2013-08-18 91 views
1

我有一些代碼,目前看起來有點像這樣:執行功能,有條件和並行

Parallel.Invoke(
    MyFunction1, 
    MyFunction2, 
    MyFunction3, 
    MyFunction4, 
    MyFunction5); 

這個作品真的很好。現在我也有則傳遞作爲參數字節的列表,看起來像這樣:

TheList = new List<Byte>{1, 3, 5, 6 }; 

我想根據該列表的內容來執行功能。比方說,這個列表中的每個值相關聯的執行一定的功能,如:

1: MyFunction1, 
2: MyFunction2, 
... 
6: MyFunction6 

這些函數的實際名稱是不同的。

如何更改我的代碼,以便函數調用可以並行有條件地執行到字節列表的內容?例如,如果列表包含1和5,那麼代碼將只執行MyFunction1和MyFunction5,並行執行。

謝謝。

回答

2

這個怎麼樣?

Dictionary<byte, Action> actions = new Dictionary<byte, Action>() 
{ 
    { 1, MyFunction1 }, 
    { 2, MyFunction2 }, 
    ... 
    { 6, MyFunction6 } 
}; 

List<byte> actionList = new List<byte>() { 1, 3, 5, 6 }; 

Parallel.Invoke((from action in actionList select actions[action]).ToArray()); 
+0

這看起來很棒;謝謝! – frenchie

+0

不客氣。很高興我能幫上忙。 :) – Jashaszun