Fel*_*ceM 5 c# class timer event-handling
我在类中有一个方法,从/向Form1接收和返回多个参数.我需要使用定时事件来使用这些参数执行一些代码.我已经安排了这个简化的代码来显示动态:
class Motor
{
public static System.Timers.Timer _timer;
int valReg = 30;
public void PID(decimal _actualSpeed, Decimal _speedRequest, out Decimal _pwmAuto, out decimal _preValReg)
{
_timer = new System.Timers.Timer();
_timer.Interval = (3000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timerAutoset);
_timer.Enabled = true;
// {....}
_pwmAuto = valReg;
_preValReg = valReg - 1;
}
static void _timerAutoset(object sender, System.Timers.ElapsedEventArgs e)
{
/* here I need to work with:
_actualSpeed
_speedRequest
_pwmAuto
_preValReg
and send back the last two variables
*/
}
}
Run Code Online (Sandbox Code Playgroud)
这是我从Form1按钮传递和接收变量的方法:
private void button4_Click(object sender, EventArgs e)
{
// some code ................
Motor mtr = new Motor();
mtr.PID(speedRequest, actualSpeed, out pwmAuto, out xxx);
//..more code
Run Code Online (Sandbox Code Playgroud)
如何将这些参数传递给_timerAutoset事件/从_timerAutoset事件中获取?
And*_*erd 10
我倾向于使用匿名委托来解决这个问题.
public void PID(decimal _actualSpeed, Decimal _speedRequest, out Decimal _pwmAuto, out decimal _preValReg)
{
_pwmAuto = valReg;
_preValReg = valReg - 1;
// Because we cannot use [out] variables inside the anonymous degegates,
// we make a value copy
Decimal pwmAutoLocal = _pwmAuto;
Decimal preValRegLocal = _preValReg;
_timer = new System.Timers.Timer();
_timer.Interval = (3000);
_timer.Elapsed += (sender, e) => { HandleTimerElapsed(_actualSpeed, _speedRequst, pwmAutoLocal, preValRegLocal); };
_timer.Enabled = true;
// {....}
}
static void HandleTimerElapsed(Decimal actualSpeed, Decimal speedRequst, Decimal pwmAuto, Decimal preValReg)
{
// (...)
}
Run Code Online (Sandbox Code Playgroud)
(当委托访问封闭块中的局部变量时,必须注意.仔细检查代码以确保存储在这些变量中的值在事件处理程序的赋值和此处理程序的调用之间不会发生变化).