我有一个以下形式的类构造函数:
protected LoginFunctions(){…..}
在此函数中,我使用以下命令调用异步函数:
var tsk = Task.Run(async () => await PrePopulateLogin());
我的麻烦是退出构造函数时PrePopulateLogin函数仍在运行。如何更改代码,以使构造函数直到PrePopulateLogin完成后才退出?
PrePopulateLogin必须是异步的。
private async Task PrePopulateLogin()
{
var vector = await JSRuntime.Current.InvokeAsync<string>("blazorExtensions.ReadCookie", "vector");
var secureNextLogon = await JSRuntime.Current.InvokeAsync<string>("blazorExtensions.ReadCookie", "SecureNextLogon");
if (secureNextLogon != null)
{
var encryptor = new AesEncryptor(SecurityConstants.SecurityKey, Convert.FromBase64String(vector));
var decryptedValue = encryptor.Decrypt(secureNextLogon);
var email = decryptedValue.Split(' ')[0].Substring(6);
var password = decryptedValue.Split(' ')[1].Substring(9);
var rememberMe = decryptedValue.Split(' ')[2].Substring(11);
if (rememberMe == "True")
{
UserModel.EmailAddress = email;
UserModel.Password = password;
UserModel.RememberUser = true;
}
}
}
答案 0 :(得分:3)
最后找到了如何使用Blazor做到这一点。
我需要从构造函数中删除该调用,而是重写BlazorComponents初始化事件,从而:
protected override async Task OnInitAsync()
{
await PrePopulateLogin();
}