2011-08-28 60 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); 
     }