简体   繁体   中英

Is Task.WhenAll Reporting A Task Being Completed Incorrectly A Bug?

Using .Net Framework:4.7.1 Expectation: - The simulation is started in a new task - A message box will be displayed when the simulation has completed. - The simulation will continue delaying 250ms for a duration of 30 seconds.

Problem: Task.WhenAll waits until the simulation delays. Hovering the mouse over the simulation task instance reports it as completed even though it has not. The simulation will continue to run until 30 seconds has completed then the task exists.

Is this a bug?

When Task.Delay is commented out, it works as expected.

 public partial class Form1 : Form
{
    private List<Task> m_simulations = new List<Task>();

    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        m_simulations.Add(
            Task.Run(() =>
              {
                  Simulation simulation = new Simulation();
                  simulation.StartSimulation(new TimeSpan(0, 0, 30));
              })
            );

        await Task.WhenAll(m_simulations);

        MessageBox.Show("Tasks Complete Apparently!!!");
    }
}

public class Simulation
{
    public async void StartSimulation(TimeSpan waitDuration)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();

        while (stopwatch.Elapsed <= waitDuration)
        {
            await Task.Delay(250);
        }
    }
}

By using Task.Run you're creating a task to invoke the StartSimulation method, but you're never awaiting the simulation to complete, so the task you're await ing ends after StartSimulation has begun, but before it is finished.

First, change StartSimulation to return a Task :

public async Task StartSimulation(TimeSpan waitDuration)

Then, rather than using Task.Run, just start the simulation and use the returned Task in your list of things to wait for.

    Simulation simulation = new Simulation();
    m_simulations.Add(simulation.StartSimulation(new TimeSpan(0, 0, 30));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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