'How to control and coordinate the flow of many .net console applications through text file

I have 2 .net console applications. Let's say App1 and App2

When the App1 starts running it needs to check if App2 is currently running,
if App2 is running App1 should wait (let's say 10 mins).
Same goes for app 2, they should wait each other.

To achieve this I used 2 different text files.
App1.txt, App2.txt

When any of apps starts running it writes "true" to their corresponding txt file.

Then App1 checks App2.txt and if it's true it should wait 1 minute with thread.sleep in while loop.

This is the code:
Acc1 Program

static void Main(string[] args)
{
    while (true)
    {
        while (TextFile.Read(Config.App2Path) == "true")
        {
            Thread.Sleep(60 * 1 * 1000);
        }

        DoTheWork1();
        Thread.Sleep(60 * 10 * 1000);
    }
}

Acc2 Program

static void Main(string[] args)
{
    while (true)
    {
        while (TextFile.Read(Config.App1Path) == "true")
        {
            Thread.Sleep(60 * 1 * 1000);
        }

        DoTheWork2();
        Thread.Sleep(60 * 10 * 1000);
    }
}

I set the txt file to "true" inside DoTheWork method when it starts and I set it to "false" before method is done.
When I execute this code I start with App1 and the flow was like this:
App1 executed the method and started to wait 10 mins.
App2 executed the method and started to wait 10 mins.
App1 executed the method and started to wait 10 mins.
And then App2 doesn't execute anymore, instead it gets stuck and I can hear my laptop fan spinning.



Solution 1:[1]

Files are just the wrong tool for this job. While you could probably get it to work, it will probably never work well.

A better solution would be to use use the OS to synchronize your applications. For example using a pair of named EventWaitHandles. For example:

// app1
var event1 = new EventWaitHandle (false, EventResetMode.Manual, "app1");
var event2 = new EventWaitHandle (false, EventResetMode.Manual, "app2");
event1.Set();
event2.WaitOne();

// App2
var event1 = new EventWaitHandle (false, EventResetMode.Manual, "app1");
var event2 = new EventWaitHandle (false, EventResetMode.Manual, "app2");
event2.Set();
event1.WaitOne();

That should block both applications until both are running. You might be able to use SignalAndWait instead of separate set and wait-calls, but I have not tried it.

I would also consider using some kind of message buss. That should probably allow you to do something similar, but also allow messages to be passed between the applications.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JonasH