如何每10秒运行一次功能?

时间:2015-05-18 09:34:03

标签: c# multithreading

我知道这个问题在SO上被问过很多次,但是没有一个能够解决我的问题。 我想使用线程每隔10秒调用一次函数

我有一个执行帧处理的功能。我想能够在每10秒后抓取一个帧然后处理它。我的研究表明,最好为此目的使用线程,并且,由于我需要在特定时间段后执行它,我还需要一个定时器控件。

我无法弄清楚如何将线程和计时器结合使用。此外,我尝试使用BackgroundWorker控件,在处理时,严重挂起我的应用程序。我也尝试过使用定时器控件并尝试每隔10秒调用一次该函数,但在这种情况下,如果进程超过10秒可能会导致一些问题。

任何可以告诉我如何使用线程每10秒调用一次函数的示例或源代码将非常感激。

4 个答案:

答案 0 :(得分:7)

使用 System.Windows.Forms.Timer

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 10000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    yourfunctionhere();
}

答案 1 :(得分:5)

您不一定需要线程。您可以使用await / async:

public async Task DoSomethingEveryTenSeconds()
{
   while (true)
   {
      DoSomething();
      await Task.Delay(10000);
   }
}

在此示例中,返回的任务永远不会完成;修复你需要使用其他条件而不是true

在具有GUI的应用程序中,这将通过消息循环在UI线程上执行DoSomething,就像任何其他事件(如按钮单击处理程序)一样。如果没有GUI,它将在线程池线程上运行。

答案 2 :(得分:0)

在Windows窗体应用程序中,从Visual Studio的工具箱中添加一个计时器,在“设计器”视图下双击它,然后将要每隔X秒执行的功能放入显示的功能中。确保在属性视图中启用计时器。在那里,您还可以更改间隔(以毫秒为单位)。

答案 3 :(得分:-1)

如果要运行10秒钟然后停止运行,可以使用此代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Timers;
namespace Tdo
{
    class Program
    {
      public static bool k=true;
        static void Main(string[] args)
        {
            Timer q = new Timer(10000);
            q.Elapsed += Q_Elapsed;
            q.Start();
            while(k)
            {
                Console.WriteLine(DateTime.Now);
            }
            Console.ReadKey();
        }

        private static void Q_Elapsed(object sender, ElapsedEventArgs e)
        {
            StopTheCode(ref k);
        }

        public static void StopTheCode(ref  bool flag)
        {
            flag= false;   
        }            

    }
}

此处仅写了现在的日期时间为10秒,当计时器经过时,将标志设置为false,而while停止,但请注意,这10秒将取决于设备的GHz平均执行次数。每秒的指令数会有所不同

相关问题