Using a timer to wait for processes to complete

后端 未结 2 1259
既然无缘
既然无缘 2021-01-27 07:37

Imagine there are two buttons that call an asynchronous function

  int packProcesses=0;  //the number of processes we are dealing with
    bool busy = false;  //         


        
2条回答
  •  梦如初夏
    2021-01-27 08:00

    You can move your logic from inside the handler to another method:

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

    Then you can await both them:

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

提交回复
热议问题