Solved

C# - Time Condition

Posted on 2012-03-14
10
214 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
 
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Converting C# Objects into JSON file 7 41
Expando 4 36
C# Reverse int in fast ways 6 29
Performance  Html.BeginForm vs jQuery 3 15
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

744 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now