如何创建在消息传递中心中运行的方法.订阅异步方法?



我有这段代码,但它失败了,因为它期望我的方法异步:

MessagingCenter.Subscribe<CardsViewModel, ParamViewModel>(this, "CardBtn", (s, cmdParams) =>
{
if (Counts.phaseTableSelectedCardCount != 0)
{
var canContinue = await DisplayAlert("Selector", "Changing this will remove all previously selected cards from the deck", "OK", "Cancel");
if (canContinue == false)
return;
}
var settingId = vm.SetButtons(cmdParams);
detailsLayout.Children.Clear();
IsBusy = true;
Change.cardSelection = true;
await Task.Run(() => UpdateSettingsAndGetData(settingId));
AddDetailSection();
IsBusy = false;
});

有没有办法我可以为此添加异步,如果是这样,我需要在哪里添加它?

当然,只需在参数之前添加 async 关键字即可。

MessagingCenter.Subscribe<CardsViewModel, ParamViewModel>(this, "CardBtn", async (s, cmdParams) => ...

请注意我如何在"CardBtn",之后添加async关键字。请记住,lambda 只是一个内联方法。你只是在那里声明一个方法签名,只是没有一些东西。

我看到您正在设置布尔值IsBusy,我认为它会更新 UI。请注意,您可能需要Device.BeginInvokeOnMainThread才能访问 UI 线程,因为消息传递发生在后台线程上。

相关内容