Hack Forums
[.NET] Using ThreadPools - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] Using ThreadPools (/showthread.php?tid=1412481)



Using ThreadPools - #Macklemore - Jun 24, 2011

To begin threadpools acts like a static object so if you were to use it you would just go like
PHP Code

<?php 
ThreadPool
.(method) 
Now the most common method you will use with a ThreadPool is the method to add a method which it will then create a thread to execute it.
This method is called as such
PHP Code

<?php 
public void somemethod(Object ThreadName)
{
Console.WriteLine(ThreadName.ToString());}

string threadname = "MyThread";
ThreadPool.QueueUserWorkItem(somemethod,threadname); 
The ThreadPool only allows for methods with an object parameter and if you really don't need it then just don't use it.

Now what if you had a method with parameters, well it takes a little bit of extra coding but it is plausible. Before i show the code the basis is just creating a class and having all your parameters in the constructor then having the method within that class which will draw its variables through the newly declared ones in the constructor;

PHP Code

<?php 
class threadpoolclass{
private 
string info_, info_2, info_3;
  public 
threadpoolclass(string info,string info2,string info3){
  
info_ = info;
  
info_2 = info2;
  
info_3 = info3;
  }
    public 
methodwithmultipleparameters(Object Name){
  
Console.WriteLine(info_+info_2+info_3 +Name.ToString());
  }
}
class 
main{
  public 
main(){
  
threadpoolclass tpc = new threadpoolclass("this ","is a "," example");
  
string name = "workerthread";
    
ThreadPool.QueueUserWorkItem(tpc.methodwithmultipleparameters,name);
  }
} 

That the basics of the ThreadPool class and now i just want to show one example of creating multiple threads.
PHP Code

<?php 
public void countfrom(Object start){
int start_ = (int)start;
for(
int iii = 100;start_<=iii;start_++){
  
Console.WriteLine(start_);
    }
}
public 
void startmethods(){
    for(
int ii = 0;ii<=25;ii++){
  
ThreadPool.QueueUserWorkItem(countfrom,ii);
    }
} 
So all this example is doing is creating 25 threads with all a different start number and they all count up to 100.

thanks for reading and the last thing i want to say is remember to
PHP Code

<?php 
using System
.Threading; 
while working with a ThreadPool.
🎉🎉🎉🎉🎉