等待/异步未按预期工作 [英] Await/async doesn't work as expected

查看:92
本文介绍了等待/异步未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开始使用异步/等待方式.我已经使用基于MVVM模式的WPF编写了简单的应用程序,但是它没有按我预期的那样工作.该程序的工作原理是没有异步函数:执行完执行函数后,它只会在循环函数结束后冻结和解冻.

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. 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. :)

这是我的modelview类.它继承自wpf类,其中包含标准wpf函数(如OnPropertyChanged)的定义.

Here is my modelview class. It inherits from wpf class, that contains definitions of standard wpf functions like OnPropertyChanged.

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

推荐答案

您的代码中没有异步部分.仅仅使用async关键字并不能做到这一点.如果希望将同步代码卸载到其他线程,请使用Task.Run代替:

There isn't an asynchronous part in your code. Simply using the async keyword doesn't make it so. Use Task.Run instead if you wish to offload synchronous code to a different thread:

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

指南:如果您的异步"方法内部没有await,则它不是异步的.

Guideline: If your "async" method doesn't have an await inside it, it isn't asynchronous.

这篇关于等待/异步未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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