Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I have two method “ExecuteNoQuery” (performs dbCommand.ExecuteNonQuery()) and “Query” performs (dbCommand.ExecuteReader()). Both the methods are using same connection object. In ExecuteNoQuery method a lock is implemented(using connection object) and Query method implemented with out lock. In case of multiple thred, different thread accessing both the method simultaneously then what will happen?
Note: In Query method custom connection pooling is implemented with the same object.

C#
public int ExecuteNoQuery(string sqlquery, Hashtable htData) {
try {
 lock(Myservice.dbcon)  
  {
    using (OracleCommand dbCommand = new OracleCommand(sqlquery, Myservice.dbcon)) 
        {
              int rowCount = dbCommand.ExecuteNonQuery();
              return 1;
        }
  }
}

public OracleDataReader Query(string sqlquery, Hashtable htData)
    {
        try
        {
            OracleDataReader dbReader = null;
            Random ran = new Random();
            int randomnumber = ran.Next(1,5);
           Myservice.dbcon = (OracleConnection) Myservice.htdbcon
           ["Connection_" +randomnumber];
            if (Myservice.dbcon.State != System.Data.ConnectionState.Executing 
              || Myservice.dbcon !=  System.Data.ConnectionState.Fetching)
                {
                    using (OracleCommand dbCommand = new OracleCommand(sqlquery,
                     Myservice.dbcon))
                    { 
                        dbReader = dbCommand.ExecuteReader();
                    }
                }
                return dbReader;
        }
Posted
Updated 15-Feb-13 9:09am
v2

1 solution

If some lock statement on the same object is used only in one place of the code, it is functionally equivalent to the situation when no lock is used. Isn't this obvious?

Locks implement mutial exclusion mechanism which works for only for identical lock object. If two or more blocks of code are executed under lock statement with the same lock object, the execution of all these blocks is mutually exclusive. It is not important if this is the same block of code or different block executed under the lock statement with the same lock object; in all cases, each of the blocks can be executed by only one thread at a time, other threads being delayed.

For some background on the topic, please see: http://en.wikipedia.org/wiki/Mutual_exclusion[^].

See also: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900