[Solved] C# async and await keywords not working as expected with property getter [duplicate]


When the compiler encounters await keyword it will automatically schedule a task in task scheduler. The operation waits (in a non-blocking manner) for the task to complete before continue to do the rest of the code block.

To make your code run in parallel you need to modify it into

public async Task GetDistance()
{
    var leftDTask = Task.Run(() => LeftDistance = SensorLeft.Distance);
    var rightDTask= Task.Run(() => RightDistance = SensorRight.Distance);
    await Task.WhenAll(leftDTask,rightDTask);
    Distance = RightDistance < LeftDistance ? RightDistance:LeftDistance;
}

Task.WhenAll has an overload to return Task<TResult[]> Task.WhenAll<TResult[]>. and you can replace your code into

public async Task GetDistance()
{
    var leftDTask = Task.Run(() => SensorLeft.Distance);
    var rightDTask= Task.Run(() => SensorRight.Distance);
    var results= await Task.WhenAll(leftDTask,rightDTask);
    Distance = Math.Min(results[0],results[1]);
}

However, this is not a good solution. If you want the get distance truly asynchronous, you should make an asynchronous get method rather wrap it into Task.Run.

2

solved C# async and await keywords not working as expected with property getter [duplicate]