延迟程序可视化C#

本文关键字:可视化 程序 延迟 | 更新日期: 2023-09-27 18:20:29

我已经编写了一些代码。它模拟延迟。但是方法Wait()可以是async的,所以在其中设置了async。但现在需要在Wait(()中有一个指令。我该怎么做这样的函数呢。我想到了类似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();
}

延迟程序可视化C#

如果我现在理解你的问题,你可以使用以下内容:

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