使用计时器等待过程完成

时间:2018-07-11 09:14:24

标签: c# timer async-await

想象一下有两个按钮可以调用异步函数

  int packProcesses=0;  //the number of processes we are dealing with
    bool busy = false;  //are we busy?
   int v=10;
  private async void button5_Click(object sender, EventArgs e)
  {
    packProcesses++;
    busy = true;
    Trace.WriteLine("PROCESSES " + packProcesses + " busy? " + busy);
    //Do something
    var result = await DelayAndReturnAsync(v);
    //finished?
    packProcesses--;
    if (packProcesses <= 0) busy = false;
    Trace.WriteLine("Processes " + packProcesses + " busy? " + busy);
    }

    private async void button6_Click(object sender, EventArgs e)
     {
       packProcesses++;
       busy = true;
       Trace.WriteLine("PROCESSES " + packProcesses + " busy? " + busy);

        //Do something
        var result = await DelayAndReturnAsync(v);
        //finished?
        packProcesses--;
        if (packProcesses <= 0) busy = false;
        Trace.WriteLine("Processes " + packProcesses + " busy? " + busy);
        }

其中异步函数为

 async Task<int>DelayAndReturnAsync(int val)
  {
   await Task.Delay(TimeSpan.FromSeconds(val)).ConfigureAwait(false);
   Trace.WriteLine("Time" + DateTime.Now);
    return val;
   }

,我想有另一个调用这两个按钮的按钮。 如果我只是将两个click函数一个接一个地放置,那么我将同时启动两个过程。

因为我希望一个过程在另一个过程之后开始

 private async void button8_Click(object sender, EventArgs e)
  {
  button5_Click(sender, e);
   do
    {
     await Task.Delay(1000);
     } while (busy);
    button6_Click(sender, e);
    }

我从this answer那里得到了主意

这是个好主意吗?我不想阻塞CPU来执行此操作。 是否有更好的方法来等待一个过程完成以启动另一个过程?

2 个答案:

答案 0 :(得分:2)

您可以将逻辑从处理程序内部移至另一个方法:

private async void button1_Click(object sender, EventArgs e)
{
    await Process1();
}

private async Task Process1()
{
    packProcesses++;
    busy = true;
    Trace.WriteLine("PROCESSES " + packProcesses + " busy? " + busy);
    //Do something
    var result = await DelayAndReturnAsync(v);
    //finished?
    packProcesses--;
    if (packProcesses <= 0) busy = false;
    Trace.WriteLine("Processes " + packProcesses + " busy? " + busy);
}

private async void button2_Click(object sender, EventArgs e)
{
    await Process2();
}

private async Task Process2()
{
    packProcesses++;
    busy = true;
    Trace.WriteLine("PROCESSES " + packProcesses + " busy? " + busy);

    //Do something
    var result = await DelayAndReturnAsync(v);
    //finished?
    packProcesses--;
    if (packProcesses <= 0) busy = false;
    Trace.WriteLine("Processes " + packProcesses + " busy? " + busy);
}

然后您可以等待它们:

private async void button3_Click(object sender, EventArgs e)
{
    await Process1();
    await Process2();
}

答案 1 :(得分:1)

如果可以的话,我会尽量避免让您的rccbutton6_Click方法返回button5_Click。相反,如果让他们返回void,则可以Task

await

编辑:

private async Task button5_Click(object sender, EventArgs e) 
{ ... }

private async Task button8_Click(object sender, EventArgs e) 
{
     await button5_Click(sender, e);
     await button6_Click(sender, e);
}