在 VB.NET 中,我想在再次单击按钮之前创建一个时间延迟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14153955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In VB.NET I want to create a time delay before a button can be clicked again
提问by
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?
这是一个图像主机应用程序,但是现在用户可以通过快速点击来淹没我的服务器。那么有没有办法在用户单击和再次单击之间设置 10 秒的时间延迟。如果他们确实尝试在那个时间点击它会有一个 MsgBox 警告他们在时间到之前他们不能点击?
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!
谢谢!
采纳答案by Kirill Shlenskiy
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:
根据您提到的 MsgBox 和 Threading 我假设客户端是 Windows 应用程序。您可以禁用该按钮 10 秒钟。这是一些 .NET 4.0 代码:
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:
... 或者更漂亮的 .NET 4.5 等价物:
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

