2014-08-29 75 views
2

我有這個類:如何在Action中傳遞字符串參數?

public class PCQueue : IDisposable 
{ 
    public delegate void OnFileAddDelegate(string file); 
    public event OnFileAddDelegate OnFileAddEventHandler; 
    BlockingCollection<Action> _taskQ = new BlockingCollection<Action>(); 
    public PCQueue (int workerCount) 
    { 
    // Create and start a separate Task for each consumer: 
    for (int i = 0; i < workerCount; i++) 
     Task.Factory.StartNew (Consume); 
    } 

    public void Dispose() { _taskQ.CompleteAdding(); } 

    public void EnqueueTask (Action action) { _taskQ.Add (action); } 

    void Consume() 
    { 
    // This sequence that we’re enumerating will block when no elements 
    // are available and will end when CompleteAdding is called. 
    foreach (Action action in _taskQ.GetConsumingEnumerable()) 
     action();  // Perform task. 
    } 
} 

,我有string[],我想添加到我的Queue之後,我想我的Consume()得到爲了處理這個文件。

string[] files; 

PCQueue pq = new PCQueue(1); 
foreach (string item in files) 
    pq.EnqueueTask(item); 

我有這樣的錯誤:無法從「字符串」到「System.Action」

轉換後,我把文件從我Queue我是檢查這個文件:

Checker checker = new Checker(); 
string result = Checker.Check(my file from the Queue); 
if (result != null && OnFileAddEventHandler != null) 
    OnFileAddEventHandler(result); 

如果這個文件是好的我激發了事件到我的表格

+0

當然,隊列應該包含數據,而不是任務? – 2014-08-29 08:26:16

+0

@MthetheWWatson Nope,似乎整個過程是用預定義數量的工作人員處理文件的集合,所以無論是處理「Action 」都存儲在隊列中,還是作爲「Action」的隊列。 – AndreySarafanov 2014-08-29 08:46:20

+0

@AndreySarafanov在這種情況下,您只需創建一個任務數組並使用Parallel.Invoke()來啓動它們,併爲工作項使用BlockingCollection。 – 2014-08-29 09:07:20

回答

0

如果我明白你的意圖的權利,你不需要添加一個參數到你的Action,你需要的是改變方式你可以撥打EnqueueTask方法。 例如,如果你要排隊一個ProcessFile(string filename)方法的執行,你有你的代碼改成這樣:

foreach (string item in files) 
{ 
    string filename = item; 
    pq.EnqueueTask(() => ProcessFile(filename)); 
} 

之所以作出的filename變量是避免關閉在foreach循環變量,它可以根據您使用的C#版本有害,詳見this輝煌的文章。

UPD:你似乎誤解了PCQueue類所做的事情。它的工作不是爲您存儲文件名,而是存儲您想要執行的Action,然後通過Consume()方法執行所有這些文件。這些操作不必與文件相關,它們可以是任何東西。

但我並不真正需要爲你的任務PCQueue。你使用它的方式,它只是循環你的文件沒有更高效:

Checker checker = new Checker(); 
foreach (string item in files) 
{ 
    string result = Checker.Check(my file from the Queue); 
    if (result != null && OnFileAddEventHandler != null) 
    { 
     OnFileAddEventHandler(result); 
    } 
} 
+2

不應該是'Action '? – Marco 2014-08-29 08:15:55

+0

@Serv也許我是以錯誤的方式理解了這個問題,但似乎maya remetz想要爲'PCQueue'類添加一個'string'集合,以便'_taskQ'中的每個元素都被調用相應的參數從那個集合中。 – AndreySarafanov 2014-08-29 08:21:24

+0

而當EnqueueTask打電話時該怎麼辦?我有字符串[] ARR和內部的foreach循環我只是通過項目,並不能將字符串轉換爲動作 2014-08-29 08:21:35

相關問題