JuHwon
JuHwon

Reputation: 2063

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.

Upvotes: 3

Views: 2106

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502835

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

Upvotes: 9

Justin Harvey
Justin Harvey

Reputation: 14682

If you are not awaiting anything in your two last methods, then remove the async from the declaration. In this case, creating and returning the task will be enough to achieve what you want.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

There is nothing you're awaiting on within your methods, so marking then as async is pointless. That's why ReSharper is warning you.

You should start from learning how async/await works: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

Upvotes: 3

Related Questions