Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async Methods correct? Resharper warning

in my Method RecalcChartAsync i do some time intensive stuff.. so i thought i'll do some things async.

I want to start the two Methods CreateHistogramAsync CalculatePropValuesAsync and in the meanwhile do some stuff in my RecalcChartsAsync and finally wait for it to complete.

 private async void RecalcChartsAsync()
{
    var histogram = CreateHistogramAsync();
    var propValues = CalculatePropValuesAsync();

    //do some other stuff

    await histogram;
    await propValues;
}

private async Task CreateHistogramAsync()
{
    //do some stuff
}

private async Task CalculatePropValuesAsync()
{
    //do some stuff
}

Im not sure if i am doing it the right way because ReSharper gives me the following warning at the async Keyword at CreateHistogramAsync and CalculatePropValueAsync:

This async method lacks 'await' operators and will run synchronously. Consider using the await operator to await non-blocking API calls, ...

Now i am not sure if i am using this async thing in the correct way.

like image 673
JuHwon Avatar asked Dec 03 '25 06:12

JuHwon


1 Answers

Now i am not sure if i am using this async thing in the correct way.

It doesn't sound like it. Just because you have an async method doesn't mean it's going to run on a separate thread - and it sounds like that's what you're expecting. When you execute an async method, it will run synchronously - i.e. just like normal - until it hits the first await expression. If you don't have any await expressions, that means it will just run as normal, the only difference being the way that it's wrapped up in a state machine, with the completion status (exceptions etc) represented by a task.

I suspect you should change your CreateHistogramAsync and CalculatePropValuesAsync methods to be just synchronous:

private void CreateHistogram()
{
    ...
}

private void CalculatePropValues()
{
    ...
}

and use Task.Run to execute them in parallel:

private async void RecalcChartsAsync()
{
    var histogram = Task.Run((Action) CreateHistogram);
    var propValues = Task.Run((Action) CalculatePropValues);

    //do some other stuff

    await histogram;
    await propValues;
}
like image 100
Jon Skeet Avatar answered Dec 04 '25 20:12

Jon Skeet