Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prevent multithreaded access to a method or only one thread at a time 1

Status
Not open for further replies.

dalchri

Programmer
Apr 19, 2002
608
US
I have a windows service that works with AutoCAD and provides a class to the rest of the network via remoting. It is running in Singleton mode which means only one instance gets created for calls from multiple clients.

The problem that I have having is that it gets rickety if more than one client calls a method on the class simultaneously. Now, I don't know if this actually results in multiple threads being created, but I do know that the same method code is being executed simultaneously and is accessing the same instance of class level variables at the same time.

I know that I can create a hack as follows:
Code:
//class level variable
bool m_blnInUse = false;

void MethodToOnlyExecuteOneAtATime() {
//If called more than once, the code gets
//stuck here until the first call finishes
while (m_blnInUse) {}

m_blnInUse = true;
try {
   //Actual method code executes here
} finally {
   m_blnInUse = false;
}
}

Basically I just want one call to finish before another starts and the other calls to wait in line.

Is there a way to prevent this using attributes or some other mechanism built into .net? Is there a name for this concept that I can search further on such as "Thread Safety"? If code is executing more than once, does that necessitate more than one thread or can all this be happening on the same thread?
 
Read on lock() statement. Normally, you pass this to acquire exclusive locks on instance fields. If you're protecting static fields, pass a System.Type object using typeof.

hope this helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top