Click here to Skip to main content
14,607,162 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi. I've created a data logger that once the form is loaded, it checks for an .ini file if it has the serial number of the unit to be tested. It checks the .ini file every 5 seconds and display the string in a listbox. On the other hand, I have a button 'start' to start the logging process, I havent finished the logging process, but what I have right now in that button_click method is the time it will run depends on the operator for example 8 hrs. I used
DateTime start = DateTime.Now
DateTime stop = start.AddHours(8)
while (stop > start)
{
 //Log data
}


whenever I click the button, logger just freeze, not responding. I'm thinking that these methods are the culprits. Any suggestions on how I can implement these methods properly?
Posted
Updated 27-Aug-15 22:33pm
v2
Comments
digimanus 28-Aug-15 4:32am
   
as long while (stop > start) = true it stays in the while. So your screen freezes because you want him to do the while because it is true
Do you understand the concept of while?

Each 5 seconds? sounds like a TIMER solution
letsirhc 28-Aug-15 4:47am
   
@digimanus so what could be a better approach if I want to run a method (logging process) in a certain time(ex.8) while there is a method running every 5 seconds? I understand that while loop will not be finished until the condition is false

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

private Thread _loggerThread;
private readonly object _lockLoggerThread = new object();

private void StartLogging()
{
    StopLogging();

    var thread = new Thread(() =>
    {
        try
        {
            var end = DateTime.Now.AddHours(8);
            while (DateTime.Now < end)
            {
                // Log what you want

                Thread.Sleep(5000); // wait 5 seconds
            }
        }
        catch (ThreadInterruptedException)
        {
        }
    });

    lock (_lockLoggerThread)
    {
        _loggerThread = thread;
        _loggerThread.Start();
    }
}

private void StopLogging()
{
    lock (_lockLoggerThread)
    {
        if (_loggerThread != null && _loggerThread.IsAlive)
        {
            _loggerThread.Interrupt();
        }
        _loggerThread = null;
    }
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100