首页 > 解决方案 > 在 OnAppearing 函数上添加延迟

问题描述

我想在检查我的设备的互联网连接之前添加一个延迟。我有一个函数 OnAppearing()。当页面仅在 X 秒后出现时,我的应用程序将检查设备的互联网连接。

我有 2 个问题:
1. 如何添加延迟?
2.如果我添加延迟,我的页面会在延迟开始之前先出现还是我的页面在延迟之后才会出现?

protected async override void OnAppearing()
{
    base.OnAppearing();

    //Add delay before executing the code below
    if (CrossConnectivity.Current.IsConnected){
     //Some code here
    }

}

标签: c#xamarinxamarin.forms

解决方案


使用一劳永逸的任务,您的页面将继续加载/显示。

protected async override void OnAppearing()
{
    base.OnAppearing();

    Task.Run(async () =>
    {
        await Task.Delay(TimeSpan.FromSeconds(10));
        if (CrossConnectivity.Current.IsConnected)
        {
            //Some code here

            Device.BeginInvokeOnMainThread(() =>
            {
                 // If you need to update an UI element
            });

        }
    });
 }

推荐阅读