【问题标题】:How to add an delay between methods that are performing a large task如何在执行大型任务的方法之间添加延迟
【发布时间】:2020-04-17 19:22:57
【问题描述】:

我有一个按钮单击事件,它将调用将在远程服务器上启动服务的方法。每当我必须启动大量服务器服务(例如 20)时,它就会失败。我如何确定所有服务都会正确启动并且不会失败?我读过您可以使用 Thread 或 Async Delay 在方法之间添加一些时间。我不确定哪个最好用。任何建议将不胜感激。提前致谢!

protected void StartServices_Click(object sender, EventArgs e)
{
    ServerOne_Start();
    // What should I add between these two methods that will provide some time
    // for ServerOne_Start to execute before executing ServerTwo_Start?
    ServerTwo_Start();
}

【问题讨论】:

  • 将应用程序设为“无响应”?似乎不需要在 UI 线程上运行启动/停止服务。你可以使用异步。在await Task.Run(() => // start your service); 上查找示例
  • 谢谢。我会调查的。

标签: c# multithreading asynchronous


【解决方案1】:

可能最简单的解决方案是让您的事件处理程序async 和await 成为Task.Delay。

protected async void StartServices_Click(object sender, EventArgs e)
{
    ServerOne_Start();
    await Task.Delay(TimeSpan.FromSeconds(5));
    ServerTwo_Start();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2016-03-18
    • 2018-09-28
    相关资源
    最近更新 更多