• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 850
  • Last Modified:

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

0
mcs26
Asked:
mcs26
1 Solution
 
käµfm³d 👽Commented:
Firstly in C# when you pass a variable to function is it passed as a reference or value by default.
Well, on a very technical level, everything is passed by value, but this technicality is not something you typically worry about. For your purposes, a value type (int, decimal, float, anything defined as struct, etc.) is passed by value, and a reference (anything defined as class is passed by reference). You can achieve pass-by-reference with value types by using out or ref modifiers.
0

Featured Post

NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now