简体   繁体   English

延迟程序visual C#

[英]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.但是 Wait() 方法可以是异步的,因此在其中设置了异步。 But now there needs to be an instrunction inside the Wait().但是现在Wait() 中需要有一个指令。 How do i have to make a function like that.我该如何制作这样的功能。 I thougt of something like Func<int> func = new Func<int>(getWaitingTime);我想像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();
}

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);或者干脆使用Task.Delay(time); as suggested by Ron Beyer (this way you'll need only one method instead of two) :正如 Ron Beyer 所建议的那样(这样你只需要一种方法而不是两种方法):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM