【问题标题】:Background worker while loop后台工作者while循环
【发布时间】:2011-02-04 11:56:53
【问题描述】:

我要创建的是一个后台工作程序,它每 30 秒执行几个进程。但我希望这个 while 循环在程序启动时一直执行。这是我正在使用的:

    private void watcherprocess1()
    {
        backgroundWorker1.RunWorkerAsync();

    }  
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        while(
        Thread.Sleep(30000);
        specficView2();
        makeFormlist2();
        populateListview2();
    }

我的主要问题是,我可以想出一个好的 while 循环来保持它的运行

【问题讨论】:

    标签: c#


    【解决方案1】:

    使用System.Windows.Forms.Timer

    【讨论】:

    • 请记住,这将在 UI 线程上执行事件:A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
    • @Justin:在这种情况下,考虑到相关方法的名称,这实际上可能是最好的选择......
    • 同意,只是想指出这一点,因为这是 this 和线程计时器之间的重要区别。
    【解决方案2】:

    我同意 Bobby 的观点,即 System.Threading.Timer(或 System.Timers.Timer)可能最适合这项工作。

    但如果您必须创建一个使用工作线程,我宁愿专门为该任务创建一个。运行 BackGroundWorker(它是一个 ThreadPool 线程)是一个 while 循环在您的应用程序的整个生命周期中不适合我。

    可能是这样的:

    private void watcherprocess1()
    {        
        Thread thread = new Thread(new ThreadStart(this.Work));
        thread.IsBackground = true;
        thread.Name = "My Worker.";
        thread.Start();
    }  
    
    private void Work()
    {
        while(true)
        {            
            specficView2();
            makeFormlist2();
            populateListview2();
            Thread.Sleep(30000);
        }
    }
    

    【讨论】:

      【解决方案3】:

      你在找吗

      while(true)
      

      【讨论】:

        【解决方案4】:

        我认为Timer from the Threading-Namespace 会更适合这个。它将异步计时,您可以从 Tick-Event 生成进程。

        【讨论】:

        • ...如果工作可能需要超过时间间隔(30 秒),您可能需要在工作结束时设置计时器,以调整在当前工作单元中花费的时间。否则您的后台工作人员可能会重叠,并且可以同时运行许多工作人员。通常,这是要避免的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多