Skip to main content
 首页 » 编程设计

c#之我应该如何在 C# > 4.0 中运行后台线程

2024年02月13日13zhenyulu

我主要是重复使用以前的代码片段:

 public void Start() 
        { 
            renewalThread = new Thread(() => 
            { 
 
                while (!disposed) 
                { 
                    Thread.Sleep(TimeSpan.FromSeconds(10)); 
 
                    try 
                    { 
 
                        if (LogUpdated != null) 
                            update(); 
                    } 
                    catch (Exception ex) 
                    { 
 
                    } 
                } 
 
            }); 
            renewalThread.Start(); 
        } 

有没有更优雅的方法来做到这一点,考虑新的异步/等待的东西? 与执行类似操作的解决方案的主要区别是什么

Task.run( () => 
{ 
await Task.delay(10000); 
 
update code 
}, __.LongRunning); 

请您参考如下方法:

改用定时器:

    aTimer = new System.Timers.Timer(10000); 
 
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
 
    aTimer.Enabled = true; 
 
private static void OnTimedEvent(object source, ElapsedEventArgs e) 
{ 
// do something here. 
// if this method could take longer than the intervale, disable the 
// timer at the start and re-enable at the end. 
} 

使用 Timer,您不必启动新线程。 Thread.Sleep 强制您使用一个等待的线程。如果你想每 x 秒做一些事情,这就是 System.Threading.Timer 的设计目的,它将采用一个线程池线程并在调用事件时使用它,线程只会在在事件期间使用——与 Sleep 不同。 Sleep 不准确——它可能少于您要求的时间或更多。它在 10 秒内偏离那么多的可能性为零;但它仍然不准确。使用 thread.Sleep 意味着您不能同时处理两个事件——如果您的 Timer 事件处理程序花费的时间比间隔时间长,它将同时运行两个处理程序. Timer 更容易停止——您只需调用 Stop 或 Dispose。对于 Thread.Sleep,您必须使用 Thread.Abort——并且存在数据损坏的风险(即您必须编写调用 Thread.Sleep 以这样一种方式取消线程不会破坏数据)。如果您需要在事件中的 UI 线程上执行某些操作,请使用 Forms.Timer 并且您不必处理回 UI 线程的编码(例如 Control.BeginInvoke).

我可以继续,但我想你明白了。有关详细信息,请参阅 http://bit.ly/IhxHSk