Original Post
🔒 Locked
[.net] C# make code block atomic?
Advertisement
There are lots of ways to do this, suited to different things. Without knowing more about what you're trying to do, I can't answer you for sure.
The simplest thing is to do the following:
private object lockObj = new Object();
..
void myMethod() {
lock(lockObj) {
..code..
}
}
that will prevent multiple threads from operating on myMethod of the same instance of the class.
basically think of lock() as a bit of code that sets up a list of pointers to whatever you pass it.. and any time it gets called on a pointer that is already being used (until you exit the scope) it will wait for it to become freed.
so you have to make sure you're using the right objects to lock on.. the general idea is to make the lock objects as private as possible. You could the lock object shared if you wanted to have several instances of MyClass that all have MyMethod such that only one MyMethod can be executing at one time, across any number of instances.
Other things to check out:
Monitor
Mutex
ReaderWriterLock
I've had success in googling ".net threading best practices"
By the way: I just re-read your post... Mutexes and Semaphores are the only way to synchronize different processes. Everything else is only for in-process synchronization.
The simplest thing is to do the following:
private object lockObj = new Object();
..
void myMethod() {
lock(lockObj) {
..code..
}
}
that will prevent multiple threads from operating on myMethod of the same instance of the class.
basically think of lock() as a bit of code that sets up a list of pointers to whatever you pass it.. and any time it gets called on a pointer that is already being used (until you exit the scope) it will wait for it to become freed.
so you have to make sure you're using the right objects to lock on.. the general idea is to make the lock objects as private as possible. You could the lock object shared if you wanted to have several instances of MyClass that all have MyMethod such that only one MyMethod can be executing at one time, across any number of instances.
Other things to check out:
Monitor
Mutex
ReaderWriterLock
I've had success in googling ".net threading best practices"
By the way: I just re-read your post... Mutexes and Semaphores are the only way to synchronize different processes. Everything else is only for in-process synchronization.
[MethodImpl(MethodImplOptions.Synchronized)] is a nice shortcut as well.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement