Search code examples
c#xamarin.formstimerdownload-manager

How to check for long download of data in Xamarin.forms C#


I am working on a task where we display an ActivityIndicator on users phone when the data is being downloaded. Now the current ActivityIndicator displays a label "Loading..." when the background downloading in running. But I need to update the label from "Loading..." to something like "Still Downloading..." if the download is taking more than 20 seconds.

I am trying to figure out how to use a timer functionality from C# to check if my downloading has been running past 20 seconds. As per my understanding the OnTimedEvent() only fires when the set time is elapsed, but I need to execute my download process in parallel. Below is what I am trying to accomplish.

SetTimer(20000, "Still Downloading...")
// Here while the below api call is running, if it takes more than 20 seconds to complete then fire up the event to update the loading label. 
var response = obj.GetFileData(JsonConvert.SerializeObject(inputJson)); 

Below is my timer functionality that I read from here

public static void SetTimer(int timerTime, string eventMessage)
{
    if (timerTime > 0)
    { 
        _timer = new Timer(timerTime);
        _timer.Elapsed += (sender, e) => { OnTimedEvent(eventMessage); };
        _timer.AutoReset = false;
        _timer.Enabled = true;
    }
}

public static void OnTimedEvent(string eventMessage)
{
    mylabel.text = eventMessage;
}

I am not sure if my approach of using the timer class is correct here or not. I encountered multiple posts regarding timer class but they are all talking about firing an event when the timer is elapsed but doesn't talk about running the timer in parallel to my api call.

Any help would be appreciated.


Solution

  • Do you mean the label text is not updated from "loading..." Update to "still downloading..." ?

    I think when you fire up OnTimedEvent,it may not in the MainThread(UIThread),so mylabel.text = eventMessage; will not work as expected.

    Try to run in main thread like :

    public  void OnTimedEvent(string eventMessage)
        {
            Device.BeginInvokeOnMainThread(() => { mylabel.Text = eventMessage; });
        }