Search code examples
vb.netbuttonuploadtimedelay

In VB.NET I want to create a time delay before a button can be clicked again


I am wondering if there is a way to host set a timed delay between two clicks a user can make on the same button.

It is an image host application however right now the user can flood my servers by rapidly clicking. So is there a way to set a 10 second time delay between when the user has clicked and when he can click again. And if they do try to click in that time it will have a MsgBox that warns them that they can't click until the time is up?

Please note I don't want to use Threading as I do not want to hang my program for the simple reason that it will be uploading the image at that time and there are other things on the application the user will want to do while it's uploading.

Thanks!


Solution

  • Based on you mentioning MsgBox and Threading I'm assuming that the client is a Windows application. You could just disable the button for 10 seconds. Here's some .NET 4.0 code:

    Imports System.Threading
    
    Public Class MainForm
    
        Private Sub MyButton_Click() Handles MyButton.Click
            Me.DisableButtonAsync(10)
            Me.PerformWork()
        End Sub
    
        Private Sub PerformWork()
            ' Upload image or whatever.
        End Sub
    
        Private Sub DisableButtonAsync(ByVal seconds As Int32)
            Me.MyButton.Enabled = False
    
            Dim uiScheduler = TaskScheduler.FromCurrentSynchronizationContext()
    
            Task.Factory _
                .StartNew(Sub() Thread.Sleep(seconds * 1000)) _
                .ContinueWith(Sub(t) Me.MyButton.Enabled = True, uiScheduler)
        End Sub
    
    End Class
    

    ... or the much prettier .NET 4.5 equivalent:

    Imports System.Threading
    
    Public Class MainForm
    
        Private Sub MyButton_Click() Handles MyButton.Click
            Me.DisableButtonAsync(10)
            Me.PerformWork()
        End Sub
    
        Private Sub PerformWork()
            ' Upload image or whatever.
        End Sub
    
        Private Async Sub DisableButtonAsync(ByVal seconds As Int32)
            Me.MyButton.Enabled = False
    
            Await Task.Delay(seconds * 1000)
    
            Me.MyButton.Enabled = True
        End Sub
    
    End Class