To No One in Particular...
http://www.geocities.com/jeff_louie/OOP/oop4.htm
A Static Counter
Here is the classic example of a static counter that is zero based. It
contains a
static field "uniqueID" and a thread safe static method "GetUniqueID"
that
increments the unique ID:
/// <summary>
/// Summary description for TestStatic.
/// </summary>
class TestStatic
{
*** // static stuff
*** private static int uniqueID= 0;
*** private static int GetUniqueID()
*** {
******* lock(typeof(TestStatic))
******* {
*********** return uniqueID++; // returns zero at start
******* }
*** }
*** // member stuff
*** private int identity;
*** public TestStatic()
*** {
******* this.identity= TestStatic.GetUniqueID();
*** }
*** public int Identity
*** {
******* get
******* {
*********** return identity;
******* }
*** }
}
public class Test
{
**** /// <summary>
*** /// The main entry point for the application.
*** /// </summary>
**** [STAThread]
*** static void Main(string[] args)
*** {
******* //
******* // TODO: Add code to start application here
******* //
******* TestStatic ts1= new TestStatic();
******* TestStatic ts2= new TestStatic();
******* Console.WriteLine(ts1.Identity.ToString());
******* Console.WriteLine(ts2.Identity.ToString());
******* Console.ReadLine();
*** }
}
Regards,
Jeff
My concern stems from the calls to the static getNextId() method. How
do I
do something similar to Java's synchronized so that only one call
happens to
this method at a time to avoid a race condition?<
*** Sent via Developersdex
http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!