tags:

views:

54

answers:

2

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.

A: 

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.

Mark Wilkins
I just tried creating the semaphore in a static constructor that gets called before the thread is ever launched, and I am still having the same issue.
Also, the method/process that invokes DoStuff is actually a Perl script that calls DoStuff via COM.
Is it created before DoStuff is called?
Mark Wilkins
Yes, it is created before the thread is launched and before DoStuff is called.
Does that process still exist when the semaphore is opened in the other process? I believe that if the original process creates it and then exits before another opens it, the semaphore will be destroyed.
Mark Wilkins
Yes, it still exists.
I'm unsure then. It seems that there must be some problem with access rights.
Mark Wilkins
If it was a problem with access rights I would be getting a UnauthorizedAccessException. I am able to access the semaphore in the process that creates it, but not in the other process. If the thread that created the semaphore is sleeping, would it not be accessible?
A: 

It turns out the problem was that I needed to put Global\ in front of the Semaphore name.