什么是最有效的方式来调用一个方法每20秒 [英] What's the most efficient way to call a method every 20 seconds

查看:102
本文介绍了什么是最有效的方式来调用一个方法每20秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个方法传递一个参数每20秒,
例如
公共无效ProcessPerson(IPerson人)

I would like to call a method passing a parameter every 20 seconds, e.g. public void ProcessPerson(IPerson person)

我一直在读通过不同的定时器选项,并想知道是否有人可以推荐最有效的方式做到这一点?

I’ve been reading through the different Timer options and was wondering if anybody could recommend the most efficient way to do this?

另外,有没有一种方法来保持强类型,而不是使用对象的参数,然后不得不转换为IPerson?

In addition, is there a way to keep the parameter strongly typed rather than use object and then have to convert to IPerson?

感谢您的帮助。

推荐答案

一个的 System.Threading.Timer 是你所需要的:

A System.Threading.Timer is what you need:

提供在指定的时间间隔执行方法的机制。

Provides a mechanism for executing a method at specified intervals.

使用一个TimerCallback委托指定你想要的定时器来执行的方法。计时器被构造当定时器代表被指定,并且不能被改变。该方法不执行创建该计时器的线程上;它执行由系统提供的线程池线程。

Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

另外还有的 System.Windows.Forms.Timer

There's also the System.Windows.Forms.Timer:

实现引发在用户定义的间隔事件的计时器。该定时器用于优化的Windows窗体应用程序,并且必须在窗口中使用。

Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.

这视窗计时器被设计用于UI线程使用单线程环境执行处理。

This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing.

而且不要忘记的 System.Timers.Timer

And don't forget System.Timers.Timer:

Timer组件是基于服务器的计时器,它允许你指定在此经过的事件在你的应用程序提出了一个反复出现的时间间隔。

The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application.

基于服务器的定时器是专为在多线程环境中工作线程的使用。服务器计时器可以在线程之间移动来处理引发Elapsed事件,造成比上一次引发事件的Windows计时器更精确。

The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

所以,每一个调查,并决定哪一个最你的情况。

So investigate each and decide which one works best in your case.

这篇关于什么是最有效的方式来调用一个方法每20秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆