无计谋C#异步 [英] c# async without await

查看:187
本文介绍了无计谋C#异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里的文档: http://msdn.microsoft.com/en-美国/库/ hh191443.aspx 它表明:

In documentation here: http://msdn.microsoft.com/en-us/library/hh191443.aspx it indicates that:

如果异步方法不使用等待运营商,以纪念悬挂   点,该方法执行的同步方法确实,尽管   异步修改。编译器会发出警告,这样的方法。

If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier. The compiler issues a warning for such methods.

我相信这是警告:

这异步方法缺乏'等待'运营商,并会同步运行。   请考虑使用'等待'操作,以等待非阻塞API调用,   或等待Task.Run(......)做在后台线程CPU密集型的工作。

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

然后,在一个不同的,引用链路,的http:/ /msdn.microsoft.com/en-us/library/windows/apps/hh994635.aspx 时,它显示的例子如下:

Then, in a different, referenced link, http://msdn.microsoft.com/en-us/library/windows/apps/hh994635.aspx, the example it shows is as follows:

public class Example
{
    // ...
    private async void NextMove_Click(object sender, RoutedEventArgs e)
    {
        await Task.Run(() => ComputeNextMove());
        // Update the UI with results
    }

    private async Task ComputeNextMove()
    {
        // ...
    }
    // ...
}

下面,我将假设 ComputeNextMove 基本上是同步的方法,本身没有叫计谋。这则似乎违背了发行的编译器警告(除非它是一个坏榜样......)

Here, I'll assume that ComputeNextMove is basically a synchronous method, itself, not calling await. That then would seem to contradict the issuance of a compiler warning (unless it's a bad example...)

如果我没有在我的异步调用堆栈的末尾调用.NET异步方法,如 HttpClient.GetStringAsync ,我确实想实现一些具体的长运行同步逻辑,有没有更合适的方式来做到这一点?

If I'm not calling a .net Async method at the END of my asynchronous call stack, like HttpClient.GetStringAsync and I do want to implement some concrete "long running" synchronous logic, is there a more proper way to do it?

也许我的假设是不正确的, ComputeNextMove 可以声明为私人无效ComputeNextMove()这将产生不警告。

Perhaps my assumption is incorrect, and ComputeNextMove could be declared as private void ComputeNextMove() which would yield no warnings.

推荐答案

是的,它只是一个坏榜样。

Yes, it's just a bad example.

如果 ComputeNextMove 是的真正的只是它并没有真正异步执行任何同步方法(如描述建议),它不应该被声明为异步。它应该改为为私人无效ComputeNextMove()

If ComputeNextMove is truly just a synchronous method which doesn't really do anything asynchronously (as the description suggests), it shouldn't be declared as async. It should instead be private void ComputeNextMove().

ComputeNextMove 由于使用的后台线程仍将执行 Task.Run

ComputeNextMove will still execute on a background thread due to the use of Task.Run.

我会很可能使用方法组转换,而不是一个lambda EX pression这里:

I would quite possibly use a method group conversion instead of a lambda expression here:

await Task.Run((Action) ComputeNextMove);

这篇关于无计谋C#异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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