Link to home
Start Free TrialLog in
Avatar of mcs26
mcs26

asked on

C# ThreadPool MannualResetEvent Example

Hi,

I have a few simple questions? Firstly in C# when you pass a variable to function is it passed as a reference or value by default. I understand that classes are reference types so if you pass a class to a function is this always passed as a reference?

The reason I ask is because I'm confussing myself when using the ThreadPool and the MannualResetEvent. Please see the code below. I pass a mannualresetevent to another class and in that class it the changes the state of the mannualresetevent to Set(). But nothing is passed back to the calling code. So it must be passed as reference? Just a little unclear on how it is exactly working.

Any help would be great,
Thanks,
M

Public void Main()
{
	Sim S = new Sim()
	S.Setup();

	for (int i=0; i<=10; i++)
	{
		S.SomeBigLoop();
	}
}

public Class Sim
{

	public Security[] Sec = new Security[3];
	public MannualResetEvent[] doneSec = new MannualResetEvent[3];
	
	public void Setup()
	{
		for (int i=0; i<=Security.Length; i++)
		{
			Sec[i] = new Security();
			doneSec[i] = new MannualResetEvent(false);
		}

	}	

	
	public SomeBigLoop()
	{
		for (int i=0; i<=Security.Length; i++)
		{
			donSec[i].Reset();
			Security.SetupResetEvent(doneSec[i]);
			ThreadPool.QueueUserWorkItem(Security[i].SomeCalculations);	// I know I can pass an object such a mannual reset event here but in my code there would be some other object passed			
		}

	
		WaitHandle.WaitAll(doneSec);	
	}

}

public Class Security
{

	private MannualResetEvent _doneEvent;
	
	// I know the mannualresetevent could be passed in the constructor of the class but for this example I'm not
	public void SetupResetEvent(MannualResetEvent DoneEvent)
	{
		_doneEvent = DoneEvent;
	}

	public void SomeCalculations()
	{

		// do some stuff
		_doneEvent.Set();
	}

}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial