0

I have a program that creates 10 parallel tasks and in each task I need to wait for 90 seconds and I am using Thread.Sleep(90000). It is working fine, but some times it seems that it is terminating the current thread.Operations are waiting 90 seconds did not work.

Please suggest what will be the problem.

Behzad
  • 3,502
  • 4
  • 36
  • 63
Devendra
  • 99
  • 2
  • 10

3 Answers3

1

Since you're working with tasks I would suggest NOT working with thread.sleep. I suspect what you're looking for is Task.Delay. For example

public async Task DoWork()
{
    await Task.Delay(90000);
}

This will delay the current task regardless of which thread it is being executed on and without interfering with other tasks.

Shazi
  • 1,490
  • 1
  • 10
  • 22
  • How could that help with the issue in the question ("some times it seems that it is terminating the current thread")? – svick Mar 08 '16 at 23:34
1

Use Thread.Sleep when you want to block the current thread.

Use Task.Delay when you want a logical delay without blocking the current thread.

for example:

async Task PutTaskDelay()
{
    await Task.Delay(90000); // 9sec
} 

Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.

Behzad
  • 3,502
  • 4
  • 36
  • 63
  • How could that help with the issue in the question ("some times it seems that it is terminating the current thread")? – svick Mar 08 '16 at 23:34
1

You have to use Task.Delay

  int N = 9;
  Parallel.For(0, N, async delegate(int i)
   {
                await Task.Delay(90000);
   });

Edit:

Referring to this question Parallel.For() doesn't work well with async methods.

var tasks = Enumerable.Range(0, 5).Select(async i =>
            {
                await Task.Delay(90);
            });
 await Task.WhenAll(tasks);
Community
  • 1
  • 1
Ghassen
  • 1,039
  • 12
  • 27
  • Never combine `Parallel.For` and `async`-`await`. It won't do what you think. Case in point: your code returns immediately, not after 90 s. – svick Mar 08 '16 at 23:32
  • Yes @svick that is right thank you, i have to update my answer – Ghassen Mar 09 '16 at 08:23