How can I pass multiple parameters to the callback expected by System.Threading.Timer()
in C#?
timer1[timer] = new System.Threading.Timer(databaseTrensfer, row, dueTime, inte开发者_开发知识库rval);
public void databaseTrensfer(object row,object unitID)
{
// do work here
}
How can I pass the second parameter to my databaseTrensfer
function?
Thanks in advance.
The timer callback is defined to take a single parameter:
public delegate void TimerCallback(object state);
If you need to pass several arguments to your callback, which are known when you register the callback on the Timer
constructor, then you could use a lambda:
Timer CreateTimer(object unitID)
{
object row = ...
TimeSpan dueTime = ...
TimeSpan interval = ...
return new Timer(x => DatabaseTransfer (x, unitID), row, dueTime, interval);
}
static void DatabaseTransfer(object row, object unitID)
{
....
}
Writing x => DataTransfer (x, unitID)
captures the state of your unitID
variable and is roughly equivalent to this:
Timer CreateTimer(object unitID)
{
object row = ...
TimeSpan dueTime = ...
TimeSpan interval = ...
$Temp temp = new $Temp (unitID);
return new Timer(temp.Callback, row, dueTime, interval);
}
class $Temp
{
public $Temp(object arg)
{
this.arg = arg;
}
public void Callback(object x)
{
DataTransfer (x, this.arg);
}
private object arg;
}
The compiler takes care of constructing the class and plumbing behind the scenes. See for instance an explanation about closures.
Why not create a class that has properties consisting of the additional items you want to pass in? Then just pass the actual container class.
精彩评论