0

我想知道是否有一种方法可以使所有视图模型的绑定上下文为空,然后在注销时进行垃圾收集?在我的应用程序中

async void OnLogoutClicked(object sender, EventArgs args)
        {
            try
            {
                var result = await UserLogoutRequest.Logout();

                if (result.responseCode == ResponseCodes.SUCCESS)
                {
                    DialogService.ShowSuccessToast("Logout successful");
                }
                else
                {
                    DialogService.ShowErrorToast("A server error occurred during logout");
                }
            }
            catch (Exception ex)
            {
                DialogService.ShowErrorToast("A client error occurred during logout");
            }
            finally
            {
                await DataManager.Instance.SetLoggedInUser(null);
                await DataManager.Instance.SetToken(string.Empty);
                GC.Collect(); // TODO: Figure out how to GC the ViewModels so that when user logs in again it's not using the same instance of the VM
                await AppShell.Current.GoToAsync("//Welcome");
            }
        }
    }

GC.Collect() 似乎没有做太多,因为页面仍然链接到它们的视图模型。我想我可以在页面的 OnDisappearing 中执行 BindingContext = null,但我觉得 OnDisappearing 被调用得太频繁了。我宁愿在注销时将所有页面的 BindingContext 清空,然后进行垃圾收集,但我似乎没有任何钩子可以这样做。

提前致谢。

4

0 回答 0