DateTime lastClick = DateTime.Now; object obj = new object(); int i = 0; private void Button_Click(object sender, RoutedEventArgs e) { this.IsEnabled = false; var t = (DateTime.Now - lastClick).TotalMilliseconds; i++; lastClick = DateTime.Now; System.Diagnostics.Debug.Print(t + "," + i + ";" + DateTime.Now); Thread.Sleep(2000); this.IsEnabled = true; }
以上代碼並無法解決用戶點擊兩次按鈕觸發兩次的問題,由於ui線程是單線程的,因此這個這樣會致使用戶連續點擊兩次,會兩秒後又調用Button_Click一次,輸出以下:ui
1207.069,1;2017年4月19日 13:58:22 2055.1176,2;2017年4月19日 13:58:24
因此要在this.IsEnabled = false;後面強制界面刷新,代碼以下:this
private void Button_Click(object sender, RoutedEventArgs e) { this.IsEnabled = false; DispatcherHelper.DoEvents(); var t = (DateTime.Now - lastClick).TotalMilliseconds; i++; lastClick = DateTime.Now; System.Diagnostics.Debug.Print(t + "," + i + ";" + DateTime.Now); Thread.Sleep(2000); this.IsEnabled = true; } public static class DispatcherHelper { [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void DoEvents() { DispatcherFrame frame = new DispatcherFrame(); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame); try { Dispatcher.PushFrame(frame); } catch (InvalidOperationException) { } } private static object ExitFrames(object frame) { ((DispatcherFrame)frame).Continue = false; return null; } }
DispatcherHelper.DoEvents();這個方法會強制界面刷新,問題就解決了spa