-1

I have a console app that does not terminate using a code

new System.Threading.AutoResetEvent(false).WaitOne();

What I want to achieve: I would want to run a StopWatch and if it meets a condition it will run certain file manipulating codes. And then finally after the block of code, resets the timer and wait for it to be true again to rerun.

Problem: However, upon debugging I cant get my code to go through my conditions even it has already passed the required condition.

My Code:

static void Main(string[] args)
    {
        string mutex_id = "41585f436f766572743243494d";
        using (System.Threading.Mutex mtx = new System.Threading.Mutex(false, mutex_id))
        {
            if(!mtx.WaitOne(0,false))
            {
                return;
            }
            processTimer = new Stopwatch();
            processTimer.Start();

            if (processTimer.Elapsed.Seconds > 10)
            {
                processTimer.Stop();
                fileQueue = Directory.GetFiles(ConfigurationManager.AppSettings["WatchPath"], ConfigurationManager.AppSettings["Format"]).ToList();
            }
            //process the fileQueue
            //..
            //..
            //processTimer.Reset(); -> Reset Timer to wait for another 10 sec and process again
            new System.Threading.AutoResetEvent(false).WaitOne();
        }
    }

I have used a FileSystemWatcher before but I failed to get the process correctly(Like Consecutive/Concurrent file creations and such). Tried Threading and Timers as my question.

Now I'm trying to approach this issue from a new perspective. Hope some can enlighten me with this.

Community
  • 1
  • 1
Hexxed
  • 683
  • 1
  • 10
  • 28
  • Why are you using a [`StopWatch`](https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx) rather than, say, a [`Timer`](https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx)? – Damien_The_Unbeliever Feb 21 '17 at 07:35

1 Answers1

2

There is no "try again" in your code.

The code you've written does the following:

  1. Create a mutex and lock it
  2. If it already exists, close application
  3. Start a stopwatch
  4. Check if 10 seconds elapsed (which they didn't)
  5. Create a new AutoResetEvent and wait for ever for it

You will need some loop that periodically checks if 10 seconds have passed and otherwise Sleep

Sylence
  • 2,975
  • 2
  • 24
  • 31
  • Yea figured it out few hours before. Just made an infinite `while` loop and do things. Anyway thanks. – Hexxed Feb 21 '17 at 08:17