我已将以下代码用于类似目的:
private readonly ConcurrentDictionary<string, Timer> _delayedActionTimers = new ConcurrentDictionary<string, Timer>();
private static readonly TimeSpan _noPeriodicSignaling = TimeSpan.FromMilliseconds(-1);
public void DelayedAction(Action delayedAction, string key, TimeSpan actionDelayTime)
{
Func<Action, Timer> timerFactory = action =>
{
var timer = new Timer(state =>
{
var t = state as Timer;
if (t != null) t.Dispose();
action();
});
timer.Change(actionDelayTime, _noPeriodicSignaling);
return timer;
};
_delayedActionTimers.AddOrUpdate(key, s => timerFactory(delayedAction),
(s, timer) =>
{
timer.Dispose();
return timerFactory(delayedAction);
});
}
在您的情况下,您可以像这样使用它:
DelayedAction(() =>
SetText(translate.translateText(TextToTranslate.Text, "eng", "es")),
"Translate",
TimeSpan.FromMilliseconds(250));
...该SetText
方法会将字符串分配给文本框(使用适当的调度程序进行线程同步)。