xamarin 如何防止在MAUI中按下按钮时事件加载两次?

slhcrj9b  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(130)

在我的MAUI项目中,当按钮被快速按下两次时,如何防止事件加载两次?
我希望快速按两次按钮时打开一个页面。
当你轻轻按下按钮,一个页面打开。当您快速双击时,将打开2个页面。

pinkon5k

pinkon5k1#

我用SemaphoreSlim来做这个。因为它是线程安全的。SemaphoreSlim允许线程一次执行一个任务,如果这是你想要的。
你这样定义它

private SemaphoreSlim semaphoreSlim = new(1, 1);

然后在Button_CLick事件中,您可以像这样使用它:

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

await semaphoreSlim.WaitAsync();

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

首先,您要注意CurrentCount是否为0(请参阅文档),这意味着事件已经在路上了。然后调用等待中的信号量。当你完成你的任务,你释放它和按钮是准备下一次按下。

92vpleto

92vpleto2#

您可以使用Timer来实现这一点。
我们可以添加一个变量(例如,clickCount)来记录我们在TimeSpan期间点击的次数(例如1s)。
请参考以下代码:

//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;
    }

相关问题