0

In a simple form app I'm running a constant thread when the app starts. Upon its first iteration everything goes smoothly and the thread method "Thread_ContinousChecker" works as intended. After it's run once and the the lockChecker.returnBlock() == true hits then it does not run again. Ie, does not attempt again. I have a hunch that it is something to do with the await lockChecker.checkTime() line but don't understand why, if it works once why would it stop?

Note : It only stops working if the first if statement in the Thread_ContinousChecker method hits, ie if lockChecker.returnBlock() method is true. If it's false, it continues on.

Here is my program class

    static class Program
{

    //Instantiate the lockform
    static LockForm lockForm;

    public static bool checkLockForm()
    {
        Form checker = Application.OpenForms["LockForm"];
        return (checker == null);
    }
    public static void toggleLockForm(bool theBool)
    {

        //If theBool (our condition) is true start the form
           if (theBool == true)
           {
               //Checks if form already eixsts
               if (checkLockForm() == true)
               {
                   //Starts the form
                   Application.Run(lockForm = new LockForm());                   
               }
           }
        //Now if theBool is false - we want to close down any instances of the form that we may have started
           if (theBool == false)
           {
               //This is saying if an instance of a LockForm exists
               if (checkLockForm() == false)
               {
                   //Rest of app does not close but that lockform is disabled. 
                   //lockForm.Close();
                   Application.Restart();


               }
           }
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        MyController cont = new MyController();

        //Start new thread for our lock checking 
        Thread thread = new Thread(new ThreadStart(cont.Thread_ContinuousChecker));
        thread.IsBackground = true;
        thread.Name = "Data Polling Thread";
        thread.Start();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new TrayApp());
    }

    public class MyController
    {

        public Boolean checkForm()
        {
            if (Process.GetProcessesByName("ControlApp.exe").Length > 0)
            {
                // Is running
                return true;
            }
            if (Process.GetProcessesByName("ControlApp.exe").Length == 0)
            {
                // Is not running - so start it
                return false;
            }
            return false;
        }
        public async void Thread_ContinuousChecker()
        {
            while (true)
            {

                if (checkForm() == false)
                {
                    LockLogic lockChecker = new LockLogic();
                    await lockChecker.checkTime();

                    if (lockChecker.returnBlock() == true)
                    {
                        Program.toggleLockForm(true);
                    }
                    if (lockChecker.returnBlock() == false)
                    {
                        Program.toggleLockForm(false);
                    }

                }
                Thread.Sleep(10000);

            }
        }
    }

Here is my LockLogic's .checkTime() method which I'm awaiting in the above Program class

public async Task checkTime()
    {


        // Read values back from Json file
        var serializedList = await Task.Run(() => File.ReadAllText(_filePathTimes));

        // getting a list of LockTime objects
        var lockTimeList = await Task.Run(() => (List<LockTime>)JsonConvert.DeserializeObject(serializedList, typeof(List<LockTime>), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }));

        //
        if (lockTimeList == null)
        {
            return;
        }
        if(lockTimeList.Count == 0)
        {
            return;
        }

            _lockTimes = lockTimeList;

            //Then I do a foreach loop to go through every value in the start list and add the same located value to my listOfTimes (the list of LockTime objects with start and end)
            for (int x = 0; x < _lockTimes.Count; x++)
            {
                TimeSpan start = new TimeSpan(_lockTimes[x].Start.Hour, _lockTimes[x].Start.Minute, _lockTimes[x].Start.Second);
                TimeSpan end = new TimeSpan(_lockTimes[x].End.Hour, _lockTimes[x].End.Minute, _lockTimes[x].End.Second);
                TimeSpan now = new TimeSpan(DateTime.Now.TimeOfDay.Hours, DateTime.Now.TimeOfDay.Minutes, DateTime.Now.TimeOfDay.Seconds);

                if ((now > start) && (now < end))
                {
                    _block = true;
                }
                else
                {
                    _block = false;
                }
            }


    }

A massive thanks to anyone who can spot what's going wrong.

JARRRRG
  • 917
  • 2
  • 14
  • 44

1 Answers1

0

I have a hunch that the problem is your use of Application.Run(lockForm = new LockForm());. As per http://msdn.microsoft.com/en-us/library/ms157902(v=vs.110).aspx, "This method adds an event handler to the mainForm parameter for the Closed event. The event handler calls ExitThread to clean up the application."

So, it's doing what you told it - binding the lifetime of the application to the lifetime of the newly created LockForm.

Hope this helps.

Colby Cavin
  • 492
  • 2
  • 6
  • I've tried to start the LockForm via methods such as LockForm foo = new LockForm() etc, and it just won't start. Kept crashing, so that's why I had to go and use Application.Run, any idea for a way around this? – JARRRRG May 21 '14 at 03:01
  • By "crashing," I assume you mean it failed to show the window or it threw an exception because you were trying to start a form from a background thread. I'm guessing you'll have to figure out a way to run the code that creates the form from the UI thread (http://stackoverflow.com/questions/2367718/automating-the-invokerequired-code-pattern). – Colby Cavin May 21 '14 at 03:36
  • I did read it, but I just didn't get what was going on. Perhaps I should come back to it in a day or so. Start afresh. What's even more annoying is that the thread continues once I manually close the form. – JARRRRG May 21 '14 at 05:34