World’s Ever Simplest Example to Understand Thread Pool

1. Step

//creating class that contain method which would be used for threads start method

class ContaingThreadStartMethod{

private ManualResetEvent _doneEvent;

public ContaingThreadStartMethod(ManualResetEvent doneEvent)

{

_doneEvent = doneEvent;

}

public void StartMethod(object obj){

try{

int i = (int)obj;

}

catch (Exception ex)

{

string error_msg = ex.message;

}

finally

{

_doneEvent.Set();

}

}

}

2. Step

//Creating threads and

//maintain thread pool

ThreadCount = 20; // threads to be initiated

int number = 1; // object to be passed for manupulation

ManualResetEvent[] doneEvents = new ManualResetEvent[ThreadCount];

for (int i = 0; i < ThreadCount; i++)

{

doneEvents[i] = new ManualResetEvent(false);

ContaingThreadStartMethod ctsm = new ContaingThreadStartMethod(doneEvents[i]);

ThreadPool.QueueUserWorkItem(ctsm.StartMethod, number);

}

// Wait for all threads in pool to calculation…

WaitHandle.WaitAll(doneEvents);

.


Leave a Reply

Your email address will not be published. Required fields are marked *