Solved

C# - Time Condition

Posted on 2012-03-14
10
217 Views
Last Modified: 2012-03-15
Hello everybody.
My Desktop: Windows 7 Ultimate 64 bis, Visual Studio 2010 Ultimate.
 
I'm trying to implement this routine in C# WinForm.
A condition must work within 10 minutes.
If time runs out and the condition is not satisfied, the routine stops and displays a message that has not reached the condition.

Now, within these 10 minutes the condition is satisfied, stop the clock and display a message that the condition was satisfied.

if (x >= 100)
{
       //stop the timer	
       label1.Text = "x >= 100";
}

if (timerx == 10 minutes)
{
       label1.Text = "Time over x < or != 100";

}

Open in new window


Thank you,
ocaccy
0
Comment
Question by:ocaccy
  • 4
  • 4
  • 2
10 Comments
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 167 total points
ID: 37719974
class program {
private static int value = 0;

static void Main(string[] args)
        {
            try
            {
                ThreadPool.QueueUserWorkItem(o => StartChecking());
                Thread.sleep(10000);
                value=1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }

public static void StartChecking()
        {
            var startTime = DateTime.Now;

            while(true)
            {
                if (startTime.AddMinutes(1) < DateTime.Now)
                {
                    Console.WriteLine("Time Exceeded");
                    break;
                }

                //Our Condition
                if (value > 0)
                {
                    Console.WriteLine("Condition Met!!!");
                    break;
                }

                //Lets sleep for 1 sec.
                Thread.Sleep(1000);
            }
        }

Open in new window


Above code tell you basically how to achieve this.
In winforms, however you can use BackgroundWorker for achieving Asynchronous functionality. Here is link to help you with that:-
http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 333 total points
ID: 37720083
We need more details.  How is "x" being computed?  You may need another thread to do that work on.  As BuggyCoder suggests, a BackgroundWorker() control could work.  If "x" is being computed on another thread then you can use a simple Timer on the Form to determine when 10 minutes has passed.  The timing could also be accomplished in the worker thread but we'd need to see code for that.
0
 

Author Comment

by:ocaccy
ID: 37720358
if we use

 ThreadPool.QueueUserWorkItem(o => StartChecking());
                Thread.sleep(10000);
               
will not stop processing?

If this "Thread.sleep" stop the processing, we can not use this.
 
My data is coming from the USB connection which has 6 devices interspersed by RS485/USB converter.

Every 10 seconds, send command and receive data from devices.

It turns out that to wait until all devices have a difference of  less than ±10%.

But if the data do not reach  less than ±10% in those 10 minutes, we should display a message.

If within these 10 minutes to reach less than ±10%, then we can stop the clock and show the success message.

Thank you,
ocaccy
0
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 333 total points
ID: 37720473
Alright...so you probably already have the communication with the devices all squared away.  I assume that is working without blocking the UI?

Do you need an actual "countdown" on your screen?...or just a way to stop the process after 10 minutes?
0
 

Author Comment

by:ocaccy
ID: 37720707
Yes, the communication with devices probably is ok, I think so
I need the Both!

Thank you,
ocaccy
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 333 total points
ID: 37720891
Here's a simple countdown timer:
Public Class Form1

    Private TargetDateTime As DateTime

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Timer1.Interval = 1000
        Timer1.Enabled = False
    End Sub

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        TargetDateTime = DateTime.Now.AddMinutes(10)
        UpdateTimer()
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        UpdateTimer()
    End Sub

    Private Sub UpdateTimer()
        Dim ts As TimeSpan = TargetDateTime.Subtract(DateTime.Now)
        If ts.TotalMilliseconds > 0 Then
            Label1.Text = "-" & ts.Minutes & ":" & ts.Seconds.ToString("00")
        Else
            Label1.Text = "Time's Up!"
            Timer1.Stop()
            MessageBox.Show("Done!")
            Button1.Enabled = True
        End If
    End Sub

End Class

Open in new window


If your "x" value reaches your target point then simply turn off Timer1.
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 167 total points
ID: 37721553
my idea of adding sleep in main method was to change the condition after just waiting for 10 secs. Just to let you know the method will exit even after the condition meet.

the routine that is executing the timer is running in StartChecking method.
You can process response from each usb in the startchecking method by just replacing the conditional if block with your condition..
0
 

Author Comment

by:ocaccy
ID: 37723722
Hi BuggyCoder,

I'll test your code.
If really does not sleep the access the USB port, I think is a good idea.
Idle_Mind, forgive me please.
I'm using C #, and do not have much familiarity with VB.

Thank you,
ocaccy
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 333 total points
ID: 37724519
Ha!...sorry.  I use them both and am always forgetting what zone I'm in.

Here's a C# version:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private DateTime TargetDateTime;

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            timer1.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            TargetDateTime = DateTime.Now.AddMinutes(10);
            UpdateTimer();
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateTimer();
        }

        private void UpdateTimer()
        {
            TimeSpan ts = TargetDateTime.Subtract(DateTime.Now);
            if (ts.TotalMilliseconds > 0)
            {
                label1.Text = "-" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString("00");
            }
            else
            {
                label1.Text = "Time's Up!";
                timer1.Stop();
                MessageBox.Show("Done!");
                button1.Enabled = true;
            }
        }

    }
}

Open in new window

0
 

Author Closing Comment

by:ocaccy
ID: 37727922
Thank you.
Solve two problems.

Regards,
ocaccy
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question