Scoping and Synchronization

  • Thread starter Thread starter No One
  • Start date Start date
N

No One

I have an object that needs to have a global scope within my ASP.Net
application. As I can find no way to make this a server component that
has a global scope, I have given it a static constructor for
initializing its inner parts. This is an id generator object for
inserting rows into a particular table (for various reasons the DBA
cannot make this table have a db server generated id). 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?

Thanks.
 
you could use lock keywork to allow only one thread to access the code at a
given point. the other threads will be placed in a queue.

if the id generation is just an incremental value then you can use interlock
class. it has a method called increment.

--

Regards,

Hermit Dave (D'way)
http://hdave.blogspot.com

(I hear what you're saying.. but lets try it my way first)
 
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?<
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top