How to set button visibility inside a timer thread?

I have searched all over the internet to try and find a good solution to my problem:

I have a timer:

// start timer if (_timer == null) { _timer = new Timer(); _timer.Elapsed += Timer_Elapsed; _timer.Interval = (1000 * 60) * 5; // 5 ; _timer.Start(); }

The timer elapsed method:
` public async void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
if (IsConnected())
{
var pendingWebRequests = MyRepository.GetAllPendingWebRequests();

            if (pendingWebRequests.Any())
            {
                var jobs = pendingWebRequests.Where(x => x.EntityName == "Job").ToList();

                if (jobs.Any())
                {
                    // Do some web api post..
                    var response = await SendData(allJobs);
                    if (response.Success)
                    {

                        foreach (var pendingJob in jobs)
                        {
                             MyRepository.DeletePendingWebRequest(pendingJob);
                        }

                        foreach (var job in allJobs)
                        {
                            MyRepository.DeleteJob(job);
                        }
                    }

                    RunOnUiThread(() =>
                    {
                        var totalOutboxCount = MyRepository.GetTotalOutboxCount();
                        var infoBadge = FindViewById<Button>(Resource.Id.infoBadgeBtn);

                        if (totalOutboxCount > 0)
                        {
                              infoBadge.Text = totalOutboxCount.ToString();
                              infoBadge.Visibility = ViewStates.Visible;
                         }
                         else
                         {
                              infoBadge.Visibility = ViewStates.Gone;
                         }
                   });
               }
           }
        }
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}`

On the UI MainActivity I wanted to make the badge disappear if there are no more outbox items left to send to the server. However the above code whilst debugging shows its found the button element, however nothing changes on the ui thread.

I have to user a timer because the app needs to check every 15 minutes if it has and pending web request data, the app will try to post it to the web api. Only if it has internet connection.

Everything else works I just need to update the UI so the user is informed of the status of pending web requests at all times for better user experience.

Can anyone please advise? Is there an alternative to this?

Sign In or Register to comment.