Hi @Markus Freitag , Welcome to Microsoft Q&A.
Optimizing code is more subjective, and I will give two suggestions from my own perspective.
Create event handlers for button click events: Instead of handling the state directly in the button click events, bind each button's click event to a corresponding event handler. This improves code readability and maintainability, and separates the state logic from the UI logic.
private void btnIN_Click(object sender, EventArgs e)
{
HandleSensorStateChange(StateContext.SensorState.IN);
}
private void btnSTART_Click(object sender, EventArgs e)
{
HandleSensorStateChange(StateContext.SensorState.START);
}
private void btnOUT_Click(object sender, EventArgs e)
{
HandleSensorStateChange(StateContext.SensorState.OUT);
}
private void HandleSensorStateChange(StateContext.SensorState newState)
{
if (SC.CurrentSensorState == StateContext.SensorState.Working)
{
SC.CurrentSensorState = newState;
SC.Working();
}
}
Use events instead of polling: You can use events to handle changes in the sensor state. Define a sensor state changed event in the StateContext class and raise the event when the state changes. Subscribe to this event in the main form to perform the necessary actions based on the state change.
public class StateContext
{
public event EventHandler<SensorStateChangedEventArgs> SensorStateChanged;
// ...
public void Working()
{
// ...
// Raise the sensor state changed event
SensorStateChanged?.Invoke(this, new SensorStateChangedEventArgs(CurrentSensorState));
// ...
}
}
public class SensorStateChangedEventArgs : EventArgs
{
public StateContext.SensorState NewState { get; }
public SensorStateChangedEventArgs(StateContext.SensorState newState)
{
NewState = newState;
}
}
// Subscribe to the sensor state changed event in the main form
private void Form_Load(object sender, EventArgs e)
{
SC.SensorStateChanged += SC_SensorStateChanged;
}
private void SC_SensorStateChanged(object sender, SensorStateChangedEventArgs e)
{
if (SC.CurrentSensorState == StateContext.SensorState.Working)
{
if (e.NewState == StateContext.SensorState.IN || e.NewState == StateContext.SensorState.START || e.NewState == StateContext.SensorState.OUT)
{
SC.Working();
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.