I am having a method called LoadData which gets data from DataBase and fills a DataGridView
.
I am using a Stopwatch to measure how long my method takes to finish it's job as below :
private void btnLoadData_Click(object sender, EventArgs e)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
LoadData ();
sw.Stop();
ShowTakenTime(sw.ElapsedMilliseconds);
}
I want something that can do The following :
private void MeasureTime(Method m)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
m.Invoke();
sw.Stop();
ShowTakenTime(sw.ElapsedMilliseconds);
}
so that I can pass the LoadData method to it and it does the rest for me.
MeasureTime(LoadData());
How can I do that?
Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses.
We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .
Pass a Method as a Parameter by Using the lambda Function in Java. This is a simple example of lambda, where we are using it to iterate the ArrayList elements. Notice that we're passing the lambda function to the forEach() method of the Iterable interface. The ArrayList class implements the Iterable interface.
You can pass a method as argument to another method, but in your example you are creating an argument named with_price , which is unrelated to your function. You probably want to use with_price as a default argument for a_method . In my example I'll call the new argument func . Just synonyms in this case.
For a method without parameters and returning void, you can use Action:
private void MeasureTime(Action m)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
m();
sw.Stop();
ShowTakenTime(sw.ElapsedMilliseconds);
}
If you have some parameters or a return type, use Func
If you want to pass parameters to your Method m
, use an Action<...>, for example if you want to pass an int and a string to your Method, use Action<int,string>
private void MeasureTime(Action<int, string> m)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
m(42, "Hello World");
sw.Stop();
ShowTakenTime(sw.ElapsedMilliseconds);
}
If you need to access the return value of your Method, use Func<...>:
private void MeasureTime(Func<int, string, string> m)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
var result = m(42, "Hello World");
sw.Stop();
ShowTakenTime(sw.ElapsedMilliseconds);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With