异步方法作为同步方法工作

Async method is working as syncronous mehtod

我正在尝试从 View 中的另一个方法调用 ViewModel 的异步方法,但它的行为是同步的。

查看模型:

public async Task<bool> GetReadyForUnlockWithQR()
    {
        try
        {
            SmilaHash = GetRandomeHashKey();
            var data = JsonConvert.SerializeObject(GetSmilaInfo());
            var res = await apiClient.PostAsync<String>("readyforunlockwithqr", data);
            if (res != null)
            {
                JObject json = JObject.Parse(res);
                if (json["doUnlock"] != null)
                {
                    LoginStatus = json.SelectToken("doUnlock").Value<bool>();
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            CancelPendingRequests();
            throw ex;
        }
        return false;
    }

我在客户 APIClient 文件中定义了 api 方法。上述请求可能需要一分钟才能完成。我不想停止 UI 并在视图中执行我的进一步操作。以下是我的看法:

private async void UnlockButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            await ViewModel.GetReadyForUnlockWithQR();
            DisplayQRCode();
        }
        catch(Exception ex)
        {
            if (ex is HttpRequestException)
            {
                Debug.WriteLine("Server not reachable");
                MessageBox.Show("Server not reachable");
            }
            else if (ex is OperationCanceledException)
            {
                Debug.WriteLine("Timeout exception");
                QRCodeImage.Source = null;
                QRCodeCanvas.Visibility = Visibility.Hidden;
            }
            else
            {
                Debug.WriteLine(ex.Message);
            }
        }
    }

我上面的代码理想情况下 DisplayQRCode() 函数应该在 await ViewModel.GetReadyForUnlockWithQR(); 之后立即工作;但它没有发生。 DisplayQRCode() 正在等待接收来自 ViewModel.GetReadyForUnlockWithQR() 的响应,为什么这不是逻辑异步代码。

The DisplayQRCode() is waiting to receive response from ViewModel.GetReadyForUnlockWithQR() Why is this not behaving as logical asyn code.

异步方法的行为是串行的(而不是“同步”),这正是 await 应该 要做的。

你可以把await想象成“异步等待”:方法被暂停并且不会继续传递await直到任务完成,但是它是异步等待的,所以线程被释放了(方法 returns 给它的调用者)。

I above code ideally the DisplayQRCode() function should work immediately after await ViewModel.GetReadyForUnlockWithQR(); but it is not happening.

如果你想这样做,那么你可以调用 GetReadyForUnlockWithQR 不要 await 任务直到 DisplayQRCode 完成:

var getReadyTask = ViewModel.GetReadyForUnlockWithQR();
DisplayQRCode();
await getReadyTask;