From a53c8dbe4537bda729c27a0d927ce1e9d6faca8c Mon Sep 17 00:00:00 2001 From: _aLfa_ Date: Wed, 24 Sep 2014 16:57:00 +0200 Subject: [PATCH] Use a lightweight timer to delay task This should also fix CID18182 --- src/Forms/VobSubOcr.cs | 15 +++++---------- src/Logic/Utilities.cs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/Forms/VobSubOcr.cs b/src/Forms/VobSubOcr.cs index 17ac3f1ee..5cf6ed233 100644 --- a/src/Forms/VobSubOcr.cs +++ b/src/Forms/VobSubOcr.cs @@ -14,6 +14,7 @@ using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; +using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; @@ -7351,17 +7352,11 @@ namespace Nikse.SubtitleEdit.Forms { var last = _lastAdditions[_lastAdditions.Count - 1]; numericUpDownStartNumber.Value = last.Index + 1; - Timer t = new Timer(); - t.Interval = 200; - t.Tick += t_Tick; - t.Start(); - } - } - private void t_Tick(object sender, EventArgs e) - { - (sender as Timer).Stop(); - ButtonStartOcrClick(null, null); + // Simulate a click on ButtonStartOcr in 200ms. + var uiContext = TaskScheduler.FromCurrentSynchronizationContext(); + Utilities.TaskDelay(200).ContinueWith(_ => ButtonStartOcrClick(null, null), uiContext); + } } private void VobSubOcr_Resize(object sender, EventArgs e) diff --git a/src/Logic/Utilities.cs b/src/Logic/Utilities.cs index cb868aebd..6630f6cac 100644 --- a/src/Logic/Utilities.cs +++ b/src/Logic/Utilities.cs @@ -12,6 +12,7 @@ using System.Net; using System.Reflection; using System.Text; using System.Text.RegularExpressions; +using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; @@ -4115,5 +4116,17 @@ namespace Nikse.SubtitleEdit.Logic return text; } + /// + /// Creates a task that will complete after a time delay. + /// + /// The number of milliseconds to wait before completing the returned task. + /// A task that represents the time delay. + public static Task TaskDelay(int millisecondsDelay) + { + var tcs = new TaskCompletionSource(); + var t = new System.Threading.Timer(_ => tcs.SetResult(null)); + t.Change(millisecondsDelay, -1); + return tcs.Task; + } } } \ No newline at end of file