Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi everyone

we are writing logs to a .txt file for a web application, using our own class. What the class does is create a semaphore with maximum maximum no. of current entries as 1. we use this semaphore to gain write access to the log file. like this....

C#
private static Semaphore _ExceptionFileLock = new Semaphore(1, 1);


C#
try
{
  // Take Hold of File Lock
  _ExceptionFileLock.WaitOne();

  ......
  Open the file strea, write, and close....
  ......
}
catch (Exception objException)
{
  // Other Exception
  throw objException;
}
finally
{
  //Release File Lock
  _ExceptionFileLock.Release();
}


Now what I'd like to know is once we publish it on IIS and multiple users hit this application, will IIS create a global semaphore for this or for different requests will IIS create different semaphore objects resulting in exception "file is alrady in use"

Any light on semaphore with reference to IIS will be greatly appreciated.

Thanks and regards
Pawan
Posted

1 solution

I don't know about Semaphores, but with Mutexes it does (when you create it this way)
What I found worked for me was create a Mutex with a string as key. (Bad practices blabla, but it works)
This way the lock is on the string value, and that will be the same for every user.

Another way to do this is using the Singleton pattern on your logger library, if you are not already doing that.
That way it should create only a single Semaphore object, and thus hold the lock.

Hope this helps.
 
Share this answer
 
Comments
Rai Pawan 3-Dec-12 4:31am    
Thanks chris

your suggestion is appreciated. On mutex vs. semaphores here a good link to read http://www.geeksforgeeks.org/archives/9102. Furthermore as part of some testing that I did it seems that since the same IIS worker process is shared so the semaphore remains global and there are no practical chances to get exception.
Thanks again.
Pawan
Christiaan Rakowski 5-Dec-12 2:52am    
If you have only one process this way will indeed work fine, I was assuming you were using multiple ones, I should have asked. Also, thanks for the link. It was a good read.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900