Brandon Farrell
Brandon Farrell

Reputation: 83

Timer not executing whole functions...?

I am making an application that checks if there are files in a certain folder, if there is, it un-minimizes the application.

System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(tick);
aTimer.Interval = updateIterval*1000;
aTimer.Enabled = true;

 public void tick(object source, ElapsedEventArgs e)
    {
        update();
    }
 public void update()
    {
        MessageBox.Show("Tick");
        if (WorkingFiles.Length != 0)
        {
            this.WindowState = FormWindowState.Normal;
            MessageBox.Show("Normal");
        }
        else
        {
            this.WindowState = FormWindowState.Minimized;
            MessageBox.Show("Minimized");
        }
    }

I will only get the "TICK" message every 10 seconds, and I wont get either of the "Normal", or "Minimized" but if I call this function via button press it works perfectly fine. not sure if there is something inherently wrong with the way I am doing this, or if I could do it another way?

Upvotes: 0

Views: 92

Answers (3)

juanreyesv
juanreyesv

Reputation: 853

Regarding the functionality you want to achieve "I am making an application that checks if there are files in a certain folder" and because you have asked for other ways to do achieve that. I would suggest you using the FileSystemWatcher Class:

"Listens to the file system change notifications and raises events when a directory, or file in a directory, changes."

Code Example also extracted from the MSDN link and modified to your needs:

FileSystemWatcher watcher;

public void StartWatch()
{
    // Create a new FileSystemWatcher and set its properties.
    watcher = new FileSystemWatcher();
    watcher.Path = "Path to directory"; // Put the path to your directory here
    // Watch for changes in LastWrite
    watcher.NotifyFilter = NotifyFilters.LastWrite;

    // Add event handlers.
    watcher.Created += new FileSystemEventHandler(OnCreated);

    // Begin watching.
    watcher.EnableRaisingEvents = true;

}

// Define the event handlers. 
private static void OnCreated(object source, FileSystemEventArgs e)
{
    MessageBox.Show("A File has been created");
}

Upvotes: 2

Kumudu
Kumudu

Reputation: 136

You are trying to access the UI thread from a background thread. In your instance I would suggest using system.windows.forms.timer instead of System.Timers.Timer

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Most likely problem with WorkingFiles being null (or some other less obvious exception) - add try/catch and show exception information if one happens.

MessageBox.Show is blocking call - so second half of the function will not run till you "OK" the dialog box and as result it is not the best way to debug/trace. Consider using Debug.Trace to output messages to VS debug window.

Upvotes: 0

Related Questions