Xamarin form: How display activityindicator instantly while in async task?

    public async Task ShowIndicator(Func<Task> action)
    {
        actionEnabled = false;
        IndicatorVisibility = true;
        await Task.Delay(5000);
        await action.Invoke();
        IndicatorVisibility = false;
        actionEnabled = true;
    }

I am using the above code to run some Task while showing the indicator by setting the viewmodel properties of the IndicatorVisibility. If I placed the Task.Delay, it will ok but will slow down the code. If I am not placed it, the indicator won't show straightaway coz it will set to second to last indicator visibility to false.

Is it possible to wait the indicator displayed itself before execute the action from the above code?

1 answer

  • answered 2018-02-13 02:28 Supun Liyanaarachchi

    Try this code

     public Task ShowIndicator(Func<Task> action)
        {
            actionEnabled = false;
            IndicatorVisibility = true;
    
            Device.BeginInvokeOnMainThread(async () =>
            {
                await action.Invoke();
                IndicatorVisibility = false;
                actionEnabled = true;
            });
        }