Reputation: 173
I have a thread that runs all the time:
private void DoSomeStuffThread() {
Semaphore sem = new Semaphore(0, 3, "sem_DoStuff");
sem.WaitOne();
do {
//do some stuff
} while (sem.WaitOne());
}
I want to be able to only execute the stuff in the do block when something from another process says so. I am trying to use the "sem_DoStuff" named system semaphore to allow this to happen.
The code that gets executed in my other process:
public string DoStuff() {
try {
Semaphore sem = Semaphore.OpenExisting("sem_DoStuff");
sem.Release();
} catch (Exception e) {
return e.Message;
}
}
So, the idea is that when DoStuff gets called, the semaphore gets released, and DoSomeStuffThread stops waiting, executes what is in the do block, and then waits for DoStuff again before it is getting called. But, when DoStuff gets called, I'm getting the exception 'No handle of the given name exists.'. What am I doing wrong?
Thanks.
Upvotes: 2
Views: 3179
Reputation: 173
It turns out the problem was that I needed to put Global\ in front of the Semaphore name.
Upvotes: 3
Reputation: 41232
It seems like you have the order wrong. The semaphore sem_DoStuff
needs to exist before the thread is created (and quite possibly before the function DoStuff
is called). The method/process that invokes those should probably be the one that creates the semaphore.
Upvotes: 0