Furkan Hıdır
Furkan Hıdır

Reputation: 21

How to prevent event from loading twice on Button press in MAUI?

how can I prevent the event from loading twice when the button is pressed twice quickly in my MAUI Project?

I expect a single page to open when the button is pressed twice quickly.

When you gently touch the button, one page opens. When you quickly double click, 2 pages open.

Upvotes: 2

Views: 1789

Answers (3)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13909

You can try to use Timer to achieve this.

We could add a variable(e.g.clickCount) to record the number of times we click during a TimeSpan(e.g. 1s).

Please refer to the following code:

//define variable clickCount to record the times of clicking Button
private static int clickCount;

private void Button_Clicked(object sender, EventArgs e) 
    {
        if (clickCount < 1)
        {
            TimeSpan tt = new TimeSpan(0, 0, 0, 1, 0);

            Device.StartTimer(tt, ClickHandle);

        }
        clickCount++;
    }



    bool ClickHandle()
    {
        if (clickCount > 1)
        {
            // Minus1(_sender);
            DisplayAlert("Alert", "You have clicked more than one times during the timespan", "OK");
            System.Diagnostics.Debug.WriteLine("----add your code here");
        }
        else
        {
            // Plus1(_sender);
            DisplayAlert("Alert", "You have clicked the button one time during the timespan", "OK");
            System.Diagnostics.Debug.WriteLine("----add your code here");
        }

        clickCount = 0;

        return false;
    }

Upvotes: 1

maxikraxi
maxikraxi

Reputation: 56

I would recommend using a bool flag

Here is a little example from my custom datepicker

private bool isDatePickerOpen = false;

private async void OnShowPickerButtonPressed(object sender, EventArgs e)
        {
            if (isDatePickerOpen) return; // If the datepicker is already open  
            isDatePickerOpen = true;
           // other code
            isDatePickerOpen = false; // reset the flag.
         }

Upvotes: 2

Peter Wessberg
Peter Wessberg

Reputation: 1921

I have used SemaphoreSlim for this. Much becuase it is thread safe. SemaphoreSlim allows a thread to execute its task one at a time, if that is what you want.

you define it like this

private SemaphoreSlim semaphoreSlim = new(1, 1);

Then in your Button_CLick event you use it like this:

if(semaphoreSlim.CurrentCount == 0)
{
   return;
}

await semaphoreSlim.WaitAsync();

try
{
   // Logic for button
}
finally
{
   semaphoreSlim.Release();
}

First you guard if the CurrentCount is 0 (see the documentation), meaning that the Event is already on its way. Then you call the semaphore in a wait. When you are done with your task you release it and the button is ready for next press.

Upvotes: 1

Related Questions