Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
pradeeptp Avatar asked Sep 23 '08 07:09

pradeeptp


2 Answers

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();
like image 124
Khoth Avatar answered Nov 14 '22 21:11

Khoth


You don't say how your web service is hosted, so I'll assume it's in IIS. I don't think the file should be accessed by multiple processes unless your service runs in multiple application pools. Nevertheless, I guess you could get this error when multiple threads in one process are trying to write.

I think I'd go for the solution you suggest yourself, Pradeep, build a single object that does all the writing to the log file. Inside that object I'd have a Queue into which all data to be logged gets written. I'd have a separate thread reading from this queue and writing to the log file. In a thread-pooled hosting environment like IIS, it doesn't seem too nice to create another thread, but it's only one... Bear in mind that the in-memory queue will not survive IIS resets; you might lose some entries that are "in-flight" when the IIS process goes down.

Other alternatives certainly include using a separate process (such as a Service) to write to the file, but that has extra deployment overhead and IPC costs. If that doesn't work for you, go with the singleton.

like image 32
Martin Avatar answered Nov 14 '22 23:11

Martin