Reputation: 1322
Given a situation where I have a method SetFooInDevice()
, which I call using a property as one of the arguments:
public class Program
{
public static byte Foo { get; set; }
public static void SetFooInDevice(System.IO.Ports.SerialPort sp, byte foo)
{
var txBuffer = new List<byte>();
// Format message according to communication protocol
txBuffer.Add(foo);
sp.Write(txBuffer.ToArray(), 0, txBuffer.Count);
}
public static void Main()
{
var _rnd = new Random();
var _serialPort = new System.IO.Ports.SerialPort("COM1", 9600);
_serialPort.Open();
for (int i = 0; i < 100; i++)
{
Foo = (byte)_rnd.Next(0, 255);
SetFooInDevice(_serialPort, Foo); // <-- How to add this call to a collection?
System.Threading.Thread.Sleep(100);
}
}
}
Is it possible to add the method call to a collection, in a way that the method call can be executed when running through the collection at a later time?
I want to be able to add calls to various methods to a collection, that I can run through and execute later if conditions are met (serial port open, time interval has passed, etc.).
Upvotes: 1
Views: 71
Reputation: 1936
Try this:
public static byte Foo { get; set; }
public static void SetFooInDevice(System.IO.Ports.SerialPort sp, byte foo)
{
var txBuffer = new List<byte>();
// Format message according to communication protocol
txBuffer.Add(foo);
sp.Write(txBuffer.ToArray(), 0, txBuffer.Count);
}
public static void Main()
{
List<Action> listActions = new List<Action>(); // here you create list of action you need to execute later
var _rnd = new Random();
var _serialPort = new System.IO.Ports.SerialPort("COM1", 9600);
_serialPort.Open();
for (int i = 0; i < 100; i++)
{
Foo = (byte)_rnd.Next(0, 255);
var tmpFoo = Foo; // wee need to create local variable, this is important
listActions.Add(() => SetFooInDevice(_serialPort, tmpFoo));
System.Threading.Thread.Sleep(100);
}
foreach (var item in listActions)
{
item(); // here you can execute action you added to collection
}
}
You can check this on MS docs Using Variance for Func and Action Generic Delegates
Upvotes: 2
Reputation: 77896
You can use Action
delegate for this purpose like below
private List<Action<System.IO.Ports.SerialPort, byte>> methodCalls
= new List<Action<System.IO.Ports.SerialPort, byte>>();
Upvotes: 0