-4

I wrote a client application where I am using two threads other than the main thread.The Background thread is used to receive data through TCP IP,while after receiving I am calling another thread that will show the received data continuously using a for loop.But after every iteration the for loop needs to wait for 30 seconds.I have used Thread.sleep(30000) but the dont know why its not working,sometimes it wakes up from sleep mode before 30 seconds.I am using dot net framework 4.Please suggest some other alternatives.

 for(n=0;n<=m;n++)
 {
   //show data;
   //wait for 30 seconds
 } 
  • You have several options. You could even write you own tímer using DateTime and a Loop, if you don't like `Task.Delay` or `Thread.Sleep`. There are also `Timer`-classes, which might help you. – Jannik Jul 08 '16 at 06:23
  • 1
    Without *any* indication *how* you wait for 30 seconds, you expect us to know what's wrong? If you have problems with code not showing expected behavior, **post the code**. – nvoigt Jul 08 '16 at 06:29
  • As I said I used Thread.Sleep() there.My code looked like - for(n=0;n<=m;n++) { //show data; Thread.Sleep(30000); } – Subhodeep Bhattacharjee Jul 08 '16 at 06:45

1 Answers1

3

Timers are not accurate in .NET . You might not get 30000 exactly.

You can using Thread.Sleep(30000); Or await Task.Delay(30000) but you need to mark your method as async;

The difference is that Thread.Sleep block the current thread, while Task.Delay doesn't.

public async Task MyMethod()
{
    int n;
    int m = 100;

    for(n=0; n<=m; n++)
    {
        //show data;
        //wait for 30 seconds
        await Task.Delay(30000);
    }
}

For .NET 4, you can use this alternative:

public static Task Delay(double milliseconds)
{
    var tcs = new TaskCompletionSource<bool>();
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Elapsed += (obj, args) =>
    {
        tcs.TrySetResult(true);
    };
    timer.Interval = milliseconds;
    timer.AutoReset = false;
    timer.Start();
    return tcs.Task;
}
Community
  • 1
  • 1
Zein Makki
  • 29,485
  • 6
  • 52
  • 63