VollRahm
VollRahm

Reputation: 437

Xamarin.Forms Dispatcher.BeginInvokeOnMainThread causing deadlock on iOS

I have an activity indicator on my Page called indicator. I want to Animate it, so that it cycles through every color. For this i'm using this method:

public static async Task ActivityIndicatorRainbow(ActivityIndicator indicator, int colorDelay)
        {
            for (double i = 0; i < 1; i += 0.01)
            {
                Color c = Color.FromHsla(i, 0.5, 0.5);

                indicator.Dispatcher.BeginInvokeOnMainThread(()=> indicator.Color = c);

                await Task.Delay(colorDelay);
            }
        }

And in my ButtonPressed Method i call that using this:

activityIndicator.IsRunning = true;
await Task.Run(() => ActivityIndicatorRainbow(activityIndicator, 10));

On Android this works fine, the Indicator spins while changing colors. But on iOS the Indicator stands still until the Rainbow Task finishes and then it starts spinning.

I have already tried Device.InvokeOnMainThreadAsync() with the same results

Upvotes: 0

Views: 384

Answers (1)

Junior Jiang
Junior Jiang

Reputation: 12723

I have tested in iOS Native Develop Tools (Xcode) by using Objective-C to change color each time less than 1 second, it occurs the same phenomnenon with Xamarin Forms . Then I think ActivityIndicator in iOS not supports changing color each time less than one seconds .

Therefore ,the easy way to make it work is to modfiy code as follow with every one second to change color :

activityIndicator.IsRunning = true;
await Task.Run(() => ActivityIndicatorRainbow(activityIndicator, 1000));

If need to less than one second to change color in iOS ,you can have a try with custom renderer to custom a ActivityIndicator by using Navtive mtethod CADisplayLink or DispatchSource.Timer .

Upvotes: 2

Related Questions