async await behaving strangely in Android & iOS

SubhaMuralidharan.6484SubhaMuralidharan.6484 USMember
edited May 2016 in Xamarin.Forms

Hi,

I am using async, await to update UI on button click to indicate user that some progress is going on and I am showing loading panel onclick of button. Below is my code:

Android:

async void loginButtonGesture_Tapped(object sender, EventArgs e)
{            
    try
    {
    DependencyService.Get<Idevice>().StartLoading();
        await AsyncUpdateStatus();
    }
}


private async Task AsyncUpdateStatus()
{
            try
            {
                await Task.Run(() =>
                {
                      //Device.BeginInvokeOnMainThread is used in places to stop loading the screen
                });
           }
}

iOS:

async void loginButtonGesture_Tapped(object sender, EventArgs e)
    {            
        try
        {
        DependencyService.Get<Idevice>().StartLoading();
            await Task.Delay(40); //Required for iOS, otherwise it loading panel is keep on running
            await AsyncUpdateStatus();
        }
    }


    private async Task AsyncUpdateStatus()
    {
                try
                {

                     //await Task.Run(() => Enabling new thread also not working
                    //Device.BeginInvokeOnMainThread is used in places to stop loading the screen

               }
    }

In iOS, adding some delay and commenting Task.Run only worked in iOS. Why its so? But if I do this for Android then, Android loading panel is not working.

Tagged:

Answers

  • AdamPAdamP AUUniversity ✭✭✭✭✭

    @SubhaMuralidharan.6484 - you should be doing the first one in a background thread and then just calling the UI element in the same thread.

    For example

    void loginButtonGesture_Tapped(object sender, EventArgs e) // This is already on the UI Thread
    {        
            Task.Run(() => DependencyService.Get<Idevice>().StartLoading()); // Runs on a background thread
            AsyncUpdateStatus();
    }
    
    private void AsyncUpdateStatus()
    {
           // Update UI element as already in the UI Thread
    }
    
Sign In or Register to comment.