Search code examples
c#xamarinxamarin.formsxamarin.androidxamarin.ios

C# Wait for value to be set


I have a problem. I am using a Skiasharp canvas where I draw a circle. Now the color of the circle gets decided by a webcall, so I use this code in the beginning:

public DeviceControl()
{
    NavigationPage.SetHasNavigationBar(this, false);
    InitializeComponent();

    ColorHandler();
}

public Task ColorHandler(string Type)
{
    return GetColors();
}

private async Task GetColors()
{
    colorList= await App.RestService.GetColors();
    pickerMode.ItemsSource = colorList;
    selectedColor = colorList.Where(x => x.Id == myCircle.ColorId).FirstOrDefault();
}

Then after this code the app will draw the Canavas in the following void:

private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
    SKCanvas canvas = e.Surface.Canvas;
    float UnscaledWidth = e.Info.Width;
    float UnscaledHeight = e.Info.Height;

    if (selectedColor != null)
    {
        imgLedstrip.Foreground = selectedColor;
    }
    else
    {
        imgLedstrip.Foreground = Color.FromHex("#707070");
    }

    /* REST OF MY CODE, BUT IRRELEVANT */
}

But the variable selectedColor is empty, while it gets filled later on!!!

Why is my constructor not awaiting the CodeHandler()?


Solution

  • The problem is that Xamarin can't handle asynchronous await calls in the constructor and as such it will complete before the asynchronous call will.

    In fact you need to be careful when calling asynchronous / long running functions in anything relating to the UI as you can end up with deadlocks or slow UI interaction if your trying to force usage of a result.

    I would suggest that you change your code such that this function is called before you require it or at the very least don't allow any function that relies upon its results to run until it has done so.