async Methods correct? Resharper warning

后端 未结 3 1431
刺人心
刺人心 2021-01-20 18:18

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 CreateHist

相关标签:
3条回答
  • 2021-01-20 18:33

    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

    0 讨论(0)
  • 2021-01-20 18:34

    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;
    }
    
    0 讨论(0)
  • 2021-01-20 18:40

    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.

    0 讨论(0)
提交回复
热议问题