Home » Android » C# async method called twice

C# async method called twice

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m building an android app using c# and Xamarin.
I have an method that creates a countdown timer, and to not block the UI the method is async.
After the countdown is finished, the method call another method, that send something to the server. If the server respond is “true”, the second method call a third method, which also is an async method.
The problem is that the third method is being called twice, and then I see there is 2 task running in the background.

First method (countdown timer):

public async Task RunTimerToScheduledTime(DateTime dt)
    {         
        while (savedInstanceState == SavedInstanceState.OnScheduled && dt > DateTime.Now)
        {
            var sub = dt - DateTime.Now;
            RunOnUiThread(() => ScheduledCuontdownTv.Text = string.Format("{0:hh\:mm\:ss}", sub));
            await Task.Delay(1000);

            if(Convert.ToInt32(sub.TotalSeconds) == 60)
            {
                Log.Debug("WNS", "RunTimerToScheduledTime - 60 sec left");
            }

            if (Convert.ToInt32(sub.TotalSeconds) == 5)
            {
                Log.Debug("WNS", "RunTimerToScheduledTime - 5 sec left");
            }
        }
        await ScheduledRideIsDone();
}

Second method (the method that send something to server):

 public async Task ScheduledRideIsDone()
    {
        MakeLoadingLayout();
        try
        {
            var res = await Api.UpdateScheduledRideStatus(SoluVars.Me.IdString, SceheduledRideStatus.Done);
            if (!res)
            {
                GlobalMethods.ShortAlertDialog(this, "bla", "bla");
                return;
            }
            else
            {
                await MakeActive();
            }
        }
        catch (Exception ex)
        {
            Log.Debug("WNS", ex.Message);
            GlobalMethods.ShortAlertDialog(this, "bla", "bla");
        }
    }

Third method (the one that being called twice):

  public async Task MakeActive()
    {
        loadingActive.Show();
        try
        {

            var res = await Api.Transofrm(id, currentLocationCoords);
            if (res)
            {

                /// Some long tasks


                //Task that should run in the background from now on
                await Task.WhenAll(AskForCurrentCityLocation(), UpdateActiveDriverTimeStamp(), UpdateWaitingCustomerAdapter());  
            }
        }
        catch (Exception ex)
        {
            Log.Debug("WNS", ex.InnerException.ToString());
        }
    }

What is the problem here? Thank you!

Answers:

Put a breakpoint into the method, and then look into call stack who called it the second time.