How to enable two different C # applications to access the same directory in a continuous stream?

I have one piece of BackgroundWorker code in two concurrent applications. Will this code avoid the problem of accessing one resource with two processes and a smooth transition?

void bw_DoWork(object sender, DoWorkEventArgs e) { bool flag = false; System.Threading.Thread.Sleep(1000); while (flag.Equals(false)) { string dir = @"C:\ProgramData\Msgs"; try { if (Directory.GetFiles(smsdir).Length > 0) { flag = true; } } catch (Exception exc) { Logger.Log("Dir Access Exception: " + exc.Message); System.Threading.Thread.Sleep(10); } } 
+4
source share
6 answers

At one level, depending on what you are doing, there is nothing wrong with having multiple applications access the same directory or file. If he just reads the access, then by all means, both can get access to it right away.

If you have identical code in several applications, then the logical one is not going to interrupt it for synchronization, no matter what you do: each application has its own copy of the logical one and cannot change the other.

For the cross-synhronization application, I would use the Mutex class. There is a constructor that takes a string parameter that defines the name of Mutex. Mutex names are unique across all Windows, not just your application. You can do Mutex m = new Mutex(false, "MySpecialMutex"); in two different applications, and each object will refer to the same thing.

+2
source

No, this will not solve the problem, because setting a logical value and checking it is not an atomic function and, therefore, is not thread safe. You must use a Mutex or Monitor object.

See this link for more information: Monitor vs Mutex in C #

+2
source

No, it will not - at least the code that you inserted will not perform any meaningful synchronization of the process.

If you need a more detailed and useful answer, you will need to be more specific about what you are doing.

0
source

no, 'flag' is local to the scope of the method, which is local to the scope of the stream. In other words, it will also be false.

This is a lock function. Use it like this. In your class, declare a private object called gothread.

in your method write like this:

 lock(gothread) { // put your code in here, one thread will not be able to enter when another thread is already // in here } 
0
source

You should come up with some kind of synchronization scheme between processes - any locking mechanism that you use in this code does not matter if you are trying to prevent collisions between two processes, and not two threads running in the same process.

0
source

A good way to block processes like using a file. The first process creates the file and opens it with exclusive access, and then deletes it when it is completed. The second process is that the file will exist and must wait until it does, or it will fail to try to open the file exclusively.

0
source

All Articles