异步方法正确吗?Resharper警告 [英] async Methods correct? Resharper warning

查看:28
本文介绍了异步方法正确吗?Resharper警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的方法 RecalcChartAsync 中,我做了一些时间密集的事情..所以我想我会做一些异步的事情.

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

我想启动两个方法 CreateHistogramAsync CalculatePropValuesAsync 同时在我的 RecalcChartsAsync 中做一些事情,最后等待它完成.

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
}

我不确定我的做法是否正确,因为 ReSharper 在 CreateHistogramAsync 和CalculatePropValueAsync 的异步关键字中给了我以下警告:

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:

这种异步方法缺少await"操作符,将同步运行.考虑使用 await 运算符来等待非阻塞 API 调用,...

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.

推荐答案

现在我不确定我是否以正确的方式使用这个异步的东西.

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

听起来不像.仅仅因为你有一个 async 方法并不意味着它会在一个单独的线程上运行 - 听起来这就是你所期望的.当您执行一个 async 方法时,它会同步运行 - 即就像正常一样 - 直到它遇到第一个 await 表达式.如果你没有任何 await 表达式,这意味着它会正常运行,唯一的区别是它封装在状态机中的方式,使用任务表示的完成状态(异常等).

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.

我怀疑您应该将 CreateHistogramAsyncCalculatePropValuesAsync 方法更改为同步:

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

private void CreateHistogram()
{
    ...
}

private void CalculatePropValues()
{
    ...
}

并使用 Task.Run 并行执行它们:

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

这篇关于异步方法正确吗?Resharper警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆