Tristan
Tristan

Reputation: 2088

Delay Program visual C#

I have made a little bit of code. It simulates a delay. But the method Wait() can be async so a set async in it. But now there needs to be an instrunction inside the Wait(). How do i have to make a function like that. I thougt of something like Func<int> func = new Func<int>(getWaitingTime); But I'm am not sure and that alone is not enough.

public class speed
{
  public int Id { get; set; }
  public speed(int id)
  {
    this.Id = id;
  }

  public async void wait() //here is the problem
  {                          
    int waitingTime = getWaitingTime();
    Console.Writeline("string.Format("Done with {0}: {1} ms", this.Id, waitingTime));
  }

  private int getWaitingTime()
  {
     int waitingTime = new Random().Next(2000);
     System.Threading.Thread.Sleep(waitingTime);
     return waitingTime;
  }
}

for (int counter = 0; counter < 10; counter++)
{
   speed slow = new speed(counter);
   slow.wait();
}

Upvotes: 2

Views: 94

Answers (1)

Fabjan
Fabjan

Reputation: 13676

If i understand your question currectly you may use something like :

  public async void wait() //here is the problem
  {                          
    int waitingTime = await getWaitingTime();
    Console.Writeline("string.Format("Done with {0}: {1} ms", this.Id, waitingTime));
  }

  private Task<int> getWaitingTime()
  {     
     return new Task<int>.Run(() =>
     {  
        int waitingTime = new Random().Next(2000);
        System.Threading.Thread.Sleep(waitingTime);
        return waitingTime;
     });
  }

Or simply use Task.Delay(time); as suggested by Ron Beyer (this way you'll need only one method instead of two) :

    public async void wait()
    {
        int waitingTime = new Random().Next(2000);
        await Task.Delay(waitingTime);
        Console.WriteLine(waitingTime);
    }

Upvotes: 1

Related Questions