延迟程序visual C#

时间:2015-11-04 16:35:57

标签: c#

我做了一些代码。它模拟了延迟。但是Wait()方法可以是异步的,所以在它中设置async。但现在需要在Wait()中有一个instrunction。我如何制作这样的功能。我想知道Func<int> func = new Func<int>(getWaitingTime);之类的事情,但我不确定,仅此一点还不够。

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();
}

1 个答案:

答案 0 :(得分:1)

如果我现在理解你的问题,你可以使用类似的东西:

  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;
     });
  }

或者只是按照Ron Beyer的建议使用Task.Delay(time);(这样你只需要一种方法而不是两种方法):

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