2

I am using an XML file to store the values. This XML file can be accessed from multiple methods.

Private object lockObject = new object() 
Method1
 {
    Lock(this.lockObject)  
  {
      MyCommonMethod()  
  }
 } 
Timer.ElapseEvent 
{  
  Lock(this.lockObject)  
  {    
  MyCommonMethod()  
  } 
} 


   MyCommonMethod()
     {  
 // Read/Write to XML file.  
 var element = XElement.Load(path);  
 // some operations  

   element.save(path) 
} 

Now, this class is been used by multiple projects(Services) which in turn are combined in to a single project.

Can i use STATIC lock object in a class and will it work in this case of different processes??

So there are possibility that they use the file at same time and at times it gives me the error that different thread owns the file although i've kept the LOCK.

what could be the best solution in this senario? Please guide.


How about this link ...

Is there a way to check if a file is in use?

is this the best way to go for or i should go with Mutex??

Please guide..

Community
  • 1
  • 1
Learner
  • 1,490
  • 2
  • 22
  • 35

2 Answers2

3

It looks like it's not the "different app domains" problem but "different processes" problem. Anyway, you could apply stricted syncrhonizations solutions like mutex:

mutex.WaitOne();
MyCommonMethod();
mutex.ReleaseMutex();

Also, if you're using C# 4.0, you could use Memory-Mapped I/O for this purposes.

Dmitry Reznik
  • 6,812
  • 2
  • 32
  • 27
2

A static variable will not be shared among difference processes.

You can either:

  1. lock the file itself (pass the FileShare.None to FileStream constructor, then use that stream for reading XML), or
  2. use a global mutex (pass the non-empty name to Mutex constructor).

The option (1) will not block in case file is already locked (it'll just throw the exception immediately) - you'll have to "poll" the file repeatedly if you want to emulate the blocking behavior. On the other hand, the option (2) will work only as long as your application is the only one accessing the file. Pick your poison.

Community
  • 1
  • 1
Branko Dimitrijevic
  • 50,809
  • 10
  • 93
  • 167