How to send arguments (parameters) in a timerTick

2019-08-04 17:11发布

问题:

I want to do something like this:

private void ttimer_Tick(object sender, EventArgs e, char[,] imatrix)
{
    Awesome code...
}

I have a method that fills a DataGridView with images, but I need to wait like half a second every time I do it. So, my original method is something like this:

private void myMethod(char[,] imatrix)
{
    Original awesome code...
}

And I want myMethod to be the timerTick's event that runs every 500 ms. Also, I do need to send the char[,] imatrix parameter. I think that it's necessary to receive the object sender, EventArgs e in a timerTick event right? Any suggestions? Thank you!

回答1:

Assuming you already have the char[,] available locally, I would use lambdas:

char[,] imatrix = GetMyMatrix();
myTimer.Tick += (sender, args) => timer_Tick(sender, args, imatrix);

Then you should have your Tick handler call the awesome code:

private void timer_Tick(object sender, EventArgs e, char[,] imatrix)
{
    myMethod(imatrix);
    //... do something with the timer args
}

And if you don't actually intend to do anything with the event args of the timer (just want to delay calling myMethod (of awesomeness) just skip the event handler wrapper method altogether and call it directly from the lambda:

char[,] imatrix = GetMyMatrix();
myTimer.Tick += (sender, args) => myMethod(imatrix);

EDIT: Regarding one of your questions, yes, the signature requires that you use the object sender, EventArgs e parameters only. However, you don't need need to do anything with them and the lambda syntax helps you ignore them. Heck, if you want to clean it up a bit more to say "I don't care about the event syntax" you can replace the named parameters as such (although it might be debatable if this is a good practice or not):

char[,] imatrix = GetMyMatrix();
myTimer.Tick += (_, __) => myMethod(imatrix);


回答2:

You cannot change the Ticker's Tick Method Signature. Instead you can create a global variable and use that.

OR

you can use Tag property of ticker. Store your matrix there. And wherever ticker's event gets called, cast sender to Ticker and then cast its Tag property to get your matrix.



回答3:

Maybe you add a public property in the sender object, and then cast the sender method parameter to this object, giving you access to the char[,] matrix data.