Skip to main content
gamedev.net
🔒 Locked

[.net] C# make code block atomic?

Started by homer_3 4 replies 8.6k views
Original Post
homer_3
homer_3
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?
Promit
Promit
No, not exactly. Use a lock to guard shared data. All other threads will block if they try to take that lock.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
matchu
matchu
You should look at the "lock" keyword or the [Synchronization] attribute.

Hope that helps
kbirger
kbirger
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.
ernow
ernow
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.
dilyan_rusev
dilyan_rusev
[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.