Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c# - Issue writing to single file in Web service in .NET

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

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

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...