tags:

views:

592

answers:

5

I want to send data every two minutes.

Right now, I have the following code:

using (var client = new WebClient())
{
    byte[] responseArray = client.UploadValues(Server, myNameValueCollection);
    Answer = Encoding.ASCII.GetString(responseArray);
}

I don't know how can I do this. I tried to add something like this to my code:

private void SendData()
{ 
    ...

    using (var client = new WebClient())
    {
        byte[] responseArray = client.UploadValues(Server, myNameValueCollection);
        Answer = Encoding.ASCII.GetString(responseArray);
    }
}

And call it at:

public void main(object sender, EventArgs e)
{
    Thread iThread = new Thread(new ThreadStart(SendData));
    iThread.Start();
    iThread.Sleep();
}

But no luck. My program is a C# Console Application.

+4  A: 

Your Thread Code should run a loop

while (true)
{
    ....
    Thread.Sleep(120*1000);
}
Henk Holterman
+1  A: 

You are on the right track, try something like this:

public void Main(..)
{
  new Thread(new ThreadStart(SendData)).Start();
}

public void SendData()
{
  while(true)
  {
    using (var client = new WebClient())
    {
      byte[] responseArray = client.UploadValues(Server, myNameValueCollection);
      Answer =   Encoding.ASCII.GetString(responseArray);
    }

    Thread.Sleep(120000);  // sleep for 2 mins between cycles    
  }
}
Blindy
+4  A: 

Why not use a timer? Something like:

using System.Timers;

System.Timers.Timer t1 = new System.Timers.Timer(2*60*1000  /*2mins interval*/);
t1.Elapsed += new System.Timers.ElapsedEventHandler(t1_Elapsed);
t1.Start();

void t1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  //Do your stuff.
}

But you will need an application like a form to be running continuously. i.e. Application.Run(YourObject);.

Or else create a form instead of a console and hide the form. (Not the best way.)

But I think using a timer is the way to go.

Ganesh R.
For this you should use System.Threading.Timer (no messageloop required). But as the Main() isn't doing anything else it doesn't matter a whole lot.
Henk Holterman
+2  A: 

For one, you're calling Thread.Sleep() on the original thread...not the one you just created and started.

Second of all, you have no loop that will call SendData again after the two minutes is up.

You might want to look into user a Timer rather than trying to set up the two minute loop interval with your own code...

Timer Class (System.Threading)

Justin Niessner
The time class in System.Threading is the way to go, IMO. +1
kenny
A: 

I second the use a timer, especially if you do want a regular interval regardless of the time it takes for you to actually send the data, or you want to control the behavior explicitly what happens if you are unable to complete the task within the interval.