2011-08-28 92 views
0

我一直在尋找,我需要一個解決方案,讓我添加200-300個作業,使用某個函數接受參數。我知道委託和對象作爲單個參數,但我希望有一些東西可以讓每個任務具有不同的參數,而不僅僅是對象參數。線程池參數

任何幫助將不勝感激。

回答

2

你可以做這樣的事情:

void MyMethod(int param) 
{ 
    .... 
} 

... 

ThreadPool.QueueUserWorkItem(_ => MyMethod(1)); 
ThreadPool.QueueUserWorkItem(_ => MyMethod(2)); 
ThreadPool.QueueUserWorkItem(_ => MyMethod(3)); 
... 
ThreadPool.QueueUserWorkItem(_ => MyMethod(42)); 

另一種選擇是讓MyMethod接受Object類型的參數,並使用QueueUserWorkItem第二超載:

void MyMethod(object param) 
{ 
    int value = (int)param; 
    .... 
} 

... 

ThreadPool.QueueUserWorkItem(MyMethod, 1); 
ThreadPool.QueueUserWorkItem(MyMethod, 2); 
ThreadPool.QueueUserWorkItem(MyMethod, 3); 
... 
ThreadPool.QueueUserWorkItem(MyMethod, 42); 
0

沒有什麼能夠阻止您發送對象列表作爲對象參數,因此實際上您可以將任意數量的參數傳遞給線程函數。

0

你找誰一個參數化線程開始(示例如下)

string myUrl = 'asd' 
Thread t = new Thread (new ParameterizedThreadStart(FetchUrl)); 
t.Start (myUrl); 


static void FetchUrl(object url) 
{ 
    // use url here, probably casting it to a known type before use 
} 

或者您可以使用System.Threading.Tasks發現任務..

Task.Factory.StartNew(() => { 
        File.WriteAllBytes(path, response); 
       }); 
1

簡單的示例:

 for (int i = 0; i < 100; i++) 
     { 
      System.Threading.ThreadPool.QueueUserWorkItem(k => 
      { 
       TestMethod(k); 
      }, i); 
     }