Sign in to follow this  
homer_3

[.net] C# make code block atomic?

Recommended Posts

homer_3    173
Is there a way to make a block of code atomic so no other threads/processes spawned from your process will interrupt it until you leave the block?

Share this post


Link to post
Share on other sites
kbirger    100
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.

Share this post


Link to post
Share on other sites
ernow    732
You need to define "interupt" better.

Do you mean pause or stop or abort or racing with another thread or...

In the end it is not possible without having a realtime OS. Windows is not realtime. At any given moment an interupt might cause execution to be moved to another thread.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this