c# - WPF 线程延迟

标签 c# .net wpf multithreading task

我有一个在新任务中调用的方法

// 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/

相关文章:

C# 依赖容器和构造函数

c# - 如何在WPF中重用自定义设计的窗口?

c# - 从没有 DoEvents 的 WebBrowser 控件获取 ReadyState

.net - 理解 PE 可执行文件的 .text 部分

c# - 正则表达式从js代码中提取地址

.net - 带有动态参数的 ChannelFactory 错误

c# - 将用户控件打印到 A4 页面的中心

WPF 上下文菜单设计。如何在WPF菜单项中设置背景?

c# - 无法识别的数据库格式

c# - 多线程时如何使用 HttpContext.Current?