Question

Assume I have the following code:

private async void Button_Click_0(object sender, RoutedEventArgs e)
{
    await RunTask("alfa", 1000);
}

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    await RunTask("beta", 5000);
}

private async Task RunTask(string taskname, int delay)
{
    LabelTaskStatus.Content = "Running " + taskname + "...";

    await Task.Delay(delay);

    LabelTaskStatus.Content = "Finished with " + taskname;
}

If I press button it will run task “alfa” in one second and then show the result. The second will run task “beta” and then show the result.

Assume that I start the beta task and then immediately start task alfa. A few seconds after task alfa is finished I will see the result of task beta. I don’t want to have it like that, I just want to get the result from the latest started task.

How do I get this result in a proper way? I could invent several ways to do it but I want to know how smart developers taking care of this :-). Cancelling the task is one way to deal it I guess, but what if you want keep the task running and just want to ignore the feedback to the user?

Was it helpful?

Solution

Add a field in your form that stores the currently active task.
At the beginning of each async method, set this field to an identifier for the current method.

After the async work finishes, only update the UI if this field has not changed.

OTHER TIPS

It's a question of how the UI runs async operations on other threads. When you do it in parallel it becomes unmanageable quite fast (for me anyways) so i like to use some kind of queue. The UI queues some work to be done, a thread on the other side dequeues that task and runs it and the threads update the UI only if the queue is empty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top