我有一个在新任务中调用的方法
// get the dispatcher for the UI thread
var uiDispatcher = Dispatcher.CurrentDispatcher;
Task.Factory.StartNew(() => BackgroundThreadProc(uiDispatcher));
在方法中BackgroundThreadProc()
我需要延迟几秒钟。我尝试使用 DispatcherTimer 和 task.delay 函数,但它没有用。唯一有用的是 System.Threading.Thread.Sleep(1)
但我认为 Thread.Sleep()
函数不是最佳解决方案。
这是我的功能:
public void BackgroundThreadProc(Dispatcher uiDispatcher)
{
for (var i = 0; i < 100; i++)
{
var task = Task.Delay(1000).ContinueWith(t =>
{
// create object
var animal = new Animal { Name = "test" + i };
uiDispatcher.Invoke(new Action(() => log(animal)));
});
}
}
我发现它不起作用,因为 DispatcherTimer 在 UI 线程中运行。我如何才能在 UI 线程之外的其他线程中实现函数的延迟?
更新:
现在我用定时器试了一下:
public void BackgroundThreadProc(Dispatcher uiDispatcher)
{
for (var i = 0; i < 100; i++)
{
var _delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 1000;
//_delayTimer.Enabled = true;
_delayTimer.Elapsed += delegate
{
var animal = new Animal { Name = "test" + i };
uiDispatcher.Invoke(new Action(() => log(animal)));
_delayTimer.Stop();
};
_delayTimer.Start();
}
}
最佳答案
使用 Task.Delay
异步引入延迟:
var task = Task.Delay(1000)
.ContinueWith(t => BackgroundThreadProc());
关于c# - WPF 线程延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22645169/