简体   繁体   English

等待/异步无法按预期工作

[英]Await/async doesn't work as expected

I'm getting started on async/await using.我开始使用异步/等待。 I've written simple application using WPF based on MVVM pattern, but it doesn't work as I expected.我已经使用基于 MVVM 模式的 WPF 编写了简单的应用程序,但它没有按我预期的那样工作。 The program works as there were no asynchronous functions: after executing execute function it freezes and unfreezes only after loop function ended.该程序的工作原理是没有异步函数:执行执行函数后,它只会在循环函数结束后冻结和解冻。

Please tell me what part did I get wrong.请告诉我我做错了什么部分。 I'd appreciate any feedback.我很感激任何反馈。 :) :)

Here is my modelview class.这是我的模型视图类。 It inherits from wpf class, that contains definitions of standard wpf functions like OnPropertyChanged.它继承自 wpf 类,该类包含 OnPropertyChanged 等标准 wpf 函数的定义。

public class ModelView : wpf
{
    string _state;
    public string state { get { return _state; } set { _state = value; OnPropertyChanged("state"); } }
    public DelegateCommand work { get; set; }

    public ModelView()
    {
        state = "Program started";

        work=new DelegateCommand(_work);
    }

    async void _work(object parameter)
    {
        state = "Working...";

        int j=await loop();

        state = "Done: " + j;
    }

    async Task<int> loop()
    {
        int i;
        for(i=0;i<1000000000;i++);

        return i;
    }
}

There isn't an asynchronous part in your code.您的代码中没有异步部分。 Simply using the async keyword doesn't make it so.简单地使用async关键字并不能做到这一点。 Use Task.Run instead if you wish to offload synchronous code to a different thread:如果您希望将同步代码卸载到不同的线程,请改用Task.Run

async void _work(object parameter)
{
    status = "Working...";
    int j=await Task.Run(() => loop());
    status = "Done: " + j;
}

int loop()
{
    int i;
    for(i=0;i<1000000000;i++);
    return i;
}

If you actually have an asynchronous operation, you can use that instead:如果您确实有异步操作,则可以改用它:

async void _work(object parameter)
{
    status = "Working...";
    await Task.Delay(1000);
    status = "Done: " + j;
}

Guideline: If your "async" method doesn't have an await inside it, it isn't asynchronous.指南:如果您的“异步”方法内部没有await ,则它不是异步的。

You aren't doing anything async.你没有做任何异步的事情。 The async keyword does not mean "creates another thread"; async关键字并不意味着“创建另一个线程”; it is quite complex, but basically it allows code to work with continuations when another asynchronous operation completes.它相当复杂,但基本上它允许代码另一个异步操作完成使用延续。 Good examples would include asynchronous database access, file access, network access, etc. It can also include asynchronous long-running operations via threads and Task.Run .好的例子包括异步数据库访问、文件访问、网络访问等。它还可以包括通过线程和Task.Run异步长时间运行的操作。 But: you aren't doing that .但是:你没有那样做 There is nothing incomplete to await - the code just runs on the main thread .没有不完整的await ——代码只是在主线程上运行 It only schedules a continuation when there is something incomplete to continue from .它仅在有不完整的内容要继续时才安排延续。

To quote the compiler (talking about the loop method):引用编译器(谈论loop方法):

Warning 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.考虑使用 'await' 运算符来等待非阻塞 API 调用,或使用 'await Task.Run(...)' 在后台线程上执行 CPU 密集型工作。

It looks like the problem is your loop function.看起来问题出在您的loop函数上。 Even though you have declared it as async there are no await statements in it and you should get a compiler warning as @Marc Gravell pointed out.即使您已将其声明为async但其中没有await语句,并且您应该收到编译器警告,正如@Marc Gravell 指出的那样。

The function spins through large number of loop iterations hogging the UI thread which will cause the blocking, it then returns the final value.该函数通过大量循环迭代占用 UI 线程,这将导致阻塞,然后返回最终值。

So your loop function is in fact a synchronous function.所以你的循环函数实际上是一个同步函数。 Assuming you were doing this for test purposes a good way to simulate an async operation is to use Task.Delay .假设您这样做是为了测试目的,模拟async操作的一个好方法是使用Task.Delay

For example:例如:

async Task<int> loop()
{
    await Task.Delay(5000);

    return 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM