Skip to main content
 首页 » 编程设计

c#之我们可以在 BackgroundWorker 中使用 DispatcherTimer 吗

2024年02月20日14shanyou

我有一些 WPF 应用程序。我需要在 BackgroundWorker 中执行一些代码,为此我使用了 DispatcherTimer。此外,该代码不使用 UI。

我的问题是这样可以吗?还是使用 Timer 或 while & Thread.Sleep 更好?

另外,使用 Task 和 Timer 或 DispatcherTimer 代替 BackgroundWorker 更好吗?

所以我们有两种方法可供选择。 (或更多?)

  1. BackgroundWorker 调用 DispatcherTimer ||定时器 || (While & Thread.Sleep)

  2. Task 调用 DispatcherTimer ||定时器 || (While & Thread.Sleep)

我只需要知道最佳性能解决方案。

代码如下

DispatcherTimer logManagerUpdater = new DispatcherTimer(DispatcherPriority.Background); 
BackgroundWorker logManagerWorker = new BackgroundWorker(); 
 
private void StartLogManager() 
{ 
    logManagerWorker.DoWork += new DoWorkEventHandler(logManagerWorker_DoWork); 
    logManagerWorker.RunWorkerAsync(); 
} 
 
void logManagerWorker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    if (this.logManagerWorker.CancellationPending) 
    { 
       e.Cancel = true; 
       return; 
    } 
 
    logManagerUpdater.Interval = new TimeSpan(0, 0, 10); 
    logManagerUpdater.Tick += new EventHandler(logManagerUpdater_Tick);   
    logManagerUpdater.Start(); 
} 
 
void logManagerUpdater_Tick(object sender, EventArgs e) 
{ 
   LogManagerJob();    
   LogDBManagerJob();   
} 

请您参考如下方法:

如果您的代码不使用 UI,则 DispatcherTimer 是不必要的 - 它专门用于在 Dispatcher 线程(通常是 UI 线程)上触发代码。一个普通的计时器就足够了。

此外,在您发布的代码中,您实质上是在“创建后台线程以创建后台线程”。我建议您完全删除后台工作程序,只在 StartLogManager 方法中创建计时器。