1

我有简单的代码,我想异步执行:

public async Task EncryptAsync()
{
    for (int i = 0; i < 10; i++)
    {
        // shift bytes
        // column multiplication
        // and so on
    }
}

这就是我调用上述方法的方式:

private async void Encryption()
{
    ShowBusyIndicator();

    await encryptor.EncryptAsync();

    HideBusyIndicator();
}

关键是,当我添加await Task.Delay(1000);此方法时,会显示 busi 指示器,但 1 秒后,应用程序锁定并同步等待加密完成。如果我删除 Task.Delay,应用程序锁定并在操作完成后解锁。

在我的情况下如何正确使用 await 和 asyc?我想简单地encryptor.EncryptAsync()异步执行方法。

4

1 回答 1

4

The async / await keywords do not allow you to create new asynchrony; instead, they simply allow you to wait for an existing asynchronous operation to complete.

You want to run your CPU-bound operation on a background thread to avoid blocking the UI.
To do that, call the synchronous blocking method inside a lambda passed to Task.Run().

You can then use await to wait for the resulting asynchronous operation (a Task instance).

于 2013-06-02T19:57:40.510 回答