Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients.

The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:

The process cannot access the file because it is being used by another process.

The solutions that I have tried to implement in C# and failed are as below.

  1. Implemented singleton class that contains code that writes to a file.
  2. Used lock statement to wrap the code that writes to the file.
  3. I have also tried to use open source logger log4net but it also is not a perfect solution.
  4. I know about logging to system event logger, but I do not have that choice.

I want to know if there exists a perfect and complete solution to such a problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

The locking is probably failing because your webservice is being run by more than one worker process. You could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using lock(someobject) {...}:

Mutex lock = new Mutex("mymutex", false);

lock.WaitOne();

// access file

lock.ReleaseMutex();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...