I am trying to call a function as per below tyo determine a pressure value but the timer does not have access to the object 'device'. What is the easiest way to fix this ? Note everything in the button function works perfect. Returns the pressure, serial number etc.
private void Button_Start_Logging_FMS_Data_Click(object sender, EventArgs e)
{
try
{
var devices = PX409Usbh.DetectDevices().ToList();
var device = devices[0];
if (devices.Count == 0)
{
MessageBox.Show("no devices found. Make sure the pressure sensor is connected");
return;
}
// Initialize each sensor so we can view the configuration and range.
foreach (var d in devices)
{
d.Initialize();
}
String Serial_Number = device.SerialNumber;
String Unit_Measurement = device.Units;
double Raw_External_Pressure = device.ReadPressure();
// Start Timer to Capture Data
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed = new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
catch (Exception ex)
{
// If exception happens, it will be returned here
Logging.Write_To_Log_File("Error", MethodBase.GetCurrentMethod().Name, "", "", ex.ToString(), "", "", "", 2);
}
}
// Specify what you want to happen when the Elapsed event is raised.
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
double Raw_External_Pressure = device.ReadPressure();
}
CodePudding user response:
Maybe use System.Threading.Timers.Timer
which lets you pass a state object to the callback method (reference) specified as an object containing information to be used by the callback method.
CodePudding user response:
You could use a lambda instead which basically just packages up the arguments you have (the sender
and args
) and appends your device
to the event handler method call.
private void Button_Start_Logging_FMS_Data_Click(object sender, EventArgs e)
{
// The start of your method here.
aTimer.Elapsed = (sender, args) => ElapsedEventHandler(sender, args, device);
// The end of your method here.
}
private void ElapsedEventHandler(object sender, ElapsedEventArgs e, Device d)
{
// Do magical things with the Device here.
}
If you don't intend on doing anything with the Timer event args, you can simplify to this:
private void Button_Start_Logging_FMS_Data_Click(object sender, EventArgs e)
{
// The start of your method here.
aTimer.Elapsed = (sender, args) => ElapsedEventHandler(device);
// The end of your method here.
}
private void ElapsedEventHandler(Device d)
{
// Do magical things with the Device here.
}