Reputation: 27633
I have an asp.net website where I would like to prevent concurrent access to certain pieces of code. Since every page request will get a thread of its own - that might be a problem.
If this were only one piece of code - I'd lock
it. However, there are actually several related methods. If one thread enters one of them - I'd like to prevent other threads from entering any of them.
How do I achieve that?
Upvotes: 1
Views: 317
Reputation: 152501
Well, you could put a lock on some object that is accessible by all of the code blocks - ideally it would be an internal
object (or private
if all of the code is in one class) so that no external code could lock it and block your code:
public class Global : System.Web.HttpApplication
{
internal static readonly object LockObject = new Object();
...
}
... meanwhile ...
lock(Global.LockObject)
{
// code block 1
}
... elsewhere ...
lock(Global.LockObject)
{
// code block 2
}
Upvotes: 2