简体   繁体   English

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

[英]How should i run a background thread in c# > 4.0

I have mainly been reusing a code snippet from old times: 我以前主要是重复使用代码片段:

 public void Start()
        {
            renewalThread = new Thread(() =>
            {

                while (!disposed)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(10));

                    try
                    {

                        if (LogUpdated != null)
                            update();
                    }
                    catch (Exception ex)
                    {

                    }
                }

            });
            renewalThread.Start();
        }

Are there more elegant ways to do this, thinking about the new async/await stuff? 是否有更优雅的方法来做到这一点,考虑新的异步/等待的东西? What are the main differences to a solution doing something like 解决方案的主要区别是什么?

Task.run( () =>
{
await Task.delay(10000);

update code
}, __.LongRunning);

Use a Timer instead: 改为使用Timer

    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.
}

With Timer you don't have to start a new thread. 使用Timer您不必启动新线程。 Thread.Sleep forces you to use a thread that sits and waits. Thread.Sleep强制你使用一个坐着等待的线程。 If you want to do something every x seconds, that's what System.Threading.Timer is designed for, it will take a thread-pool thread and use that when calling the event and the thread will only be in use during the event--unlike Sleep . 如果你想每隔x秒做一些事情,那就是System.Threading.Timer的设计目的,它将需要一个线程池线程并在调用事件时使用它,并且线程将仅在事件期间使用 - 不像Sleep Sleep is inaccurate--it could be less than the time you asked for or more. Sleep不准确 - 可能少于您要求的时间或更长时间。 the likelihood of it being that much off with 10 seconds is nil; 在10秒钟之内它的可能性是多少是零; but it's sill inaccurate. 但这是不准确的。 Using thread.Sleep means you can't do two events at once--if your Timer event handler took more time than the interval, it would run two handlers at a time. 使用thread.Sleep意味着你不能同时做两个事件 - 如果你的Timer事件处理程序花费的时间多于间隔,它将一次运行两个处理程序。 A Timer is much easier to stop--you just call Stop or Dispose . Timer更容易停止 - 您只需调用StopDispose With Thread.Sleep you have to use Thread.Abort --and risk data corruption (ie you have to write the code that calls Thread.Sleep in such a way that cancelling the thread doesn't corrupt data). 使用Thread.Sleep您必须使用Thread.Abort - 并且风险数据损坏(即您必须编写调用Thread.Sleep的代码,以便取消线程不会破坏数据)。 If you need to do something on the UI thread in the event, use Forms.Timer and you don't have to deal with marshalling back to the UI thread (eg Control.BeginInvoke ). 如果您需要在事件中的UI线程上执行某些操作,请使用Forms.Timer ,而不Forms.Timer编组处理回UI线程(例如Control.BeginInvoke )。

I could go on, but I think you get the point. 我可以继续,但我认为你明白了。 For more details, see http://bit.ly/IhxHSk 有关更多详细信息,请参阅http://bit.ly/IhxHSk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM