Home > Software engineering >  How to keep a function continuously activated
How to keep a function continuously activated

Time:09-19

I am using C# Windows Form to create an interface with another software.

  1. My software has different inputs and outputs (boolean) called DI1 DI2 DO1 DO2.
  2. On my C# app I have a function which allows the synchronization :
public void synchro() 
{
   if (switchbutton1.Checked)
      DI1 = true;
   else 
      DI1 = false;

   if (switchbutton1.Checked)
      DI2 = true;
   else 
      DI2 = false;

   if (D01 == true)
      led.Value = true; // turn on a led
   else 
      DI1 = false;

   if (D02 == true)
      led.Value = true; // turn on a led
   else 
      DI2 = false;
}

I'm beginning in C# and I want to know where I can put my function to keep it continuously synchronized. Except timers because it blinks my leds even when they are turned off.

CodePudding user response:

If you have to use this function continuously then that would be better if your Timer with interval as per your requirements. Its will call continuously and your functions will call every time.

CodePudding user response:

You should separate out the code that accesses the checkbox control, since it has thread affinity. I can't see any reason not to put it in an event handler.

As for the bit about reading the D0# registers, you can run that in an infinite loop, and execute it in an asynchronous task that you cancel and await when you unload the form.

Task _syncTask;
CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

public void switchbutton1_CheckChanged(object sender, EventArgs e) 
{
    var flag = switchbutton1.Checked;
    DI1 = flag;
    DI2 = flag;
}

public void Form_Load(object sender, EventArgs e)
{
    _syncTask = Sync(_cancellationTokenSource.Token);
}

public async void Form_Unload(object sender, EventArgs e)
{
    _cancellationTokenSource.Cancel();
    await _syncTask;
}


async Task Sync(CancellationToken token)
{
    while (!token.IsCancellationRequested)
    {
        if (D01 == true)
            led.Value = true; // turn on a led
        else 
            DI1 = false;
        if (D02 == true)
            led.Value = true; // turn on a led
        else 
            DI2 = false;
        await Task.Delay(10, token);  //Refresh 100 times per second
    }
}
  • Related