Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9173221
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T16:32:20+00:00 2026-06-17T16:32:20+00:00

I’m writing a C# wrapper, to a hardware controller using its Modbus protocol. The

  • 0

I’m writing a C# wrapper, to a hardware controller using its Modbus protocol.
The controller has 12 inputs and 12 outputs.

The wrapper has two tasks:
1. Polling the controller’s inputs at a constant interval (i.e. 50ms).
2. Running preconfigured sequences, which changes the controller’s outputs.

The sequence is XML based:

<opcode>
  <register>0</register>
  <bit>1</bit>
  <duration>500</duration>
</opcode>
<opcode>
  <register>0</register>
  <bit>0</bit>
  <duration>0</duration>
</opcode>
....

In the above sample, the controller should turn output #0 On and after 500ms turns it Off.
The pauses between operations was achieved using Thread.Sleep().
In the past I’ve used just one BackgroundWorker. When not running the sequence it did the polling.

The challenge:
The new demand for the wrapper is that it could detect changes in the controller’s inputs while running a sequence.
I’ve modified the wrapper to have 2 backgroundworkers, one for polling and the other for setting the output registers.
Each of the BackgroundWorkers calls a seperate function on the controller, they do not try to access each other data nor they share any data.

Current code:

private void workerSequence_DoWork(object sender, DoWorkEventArgs e)
{
    if (!terminating)
        if (e.Argument != null)
            DoSequence(e);
}

private void workerPoll_DoWork(object sender, DoWorkEventArgs e)
{
    if (!terminating)
    {
        DoPoll();
        Thread.Sleep(pollInterval);
    }
}

private void DoSequence(DoWorkEventArgs e)
{
    string sequenceName = e.Argument.ToString();

    foreach (configurationSequencesSequenceOpcode opcode in sequencesList[sequenceName])
    {
        if (workerSequence.CancellationPending)
            break;

        byte register = opcode.register;
        bool bit = opcode.bit;
        int duration = opcode.duration;

        SetRegister(register, bit, false);
        Thread.Sleep(duration);
    }

    e.Result = e.Argument;
}

The problem:
It’s seems like the two BackgroundWorkers interfere with each other. I’ve tried using Semaphore, Monitor.Wait() and ManualResetEvent.WaitOne() but the BackgroundWorker, which deals with the sequences, doesn’t handles them well. The main issue – its sleep duration is not consistent as before.

Any advice will be welcome.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T16:32:21+00:00Added an answer on June 17, 2026 at 4:32 pm

    Using Thread.Sleep outside of test code is generally not ideal.

    You can use System.Threading.Timer objects for both these requirements.


    EDIT if you want to prevent concurrent calls, you can use a lock to implement mutual exclusion.

    Create an object to lock on that can be seen by both timer handlers:

    public object gate = new object();
    

    For the polling, you want to set up a timer like this:

    var pollTimer = new Timer( HandlePoll, null, 0, Timeout.Infinite );
    ...
    
    void HandlePoll( object state )
    {
      lock ( gate )
      {
        DoPoll();
      }
      pollTimer.Change( pollInterval, Timeout.Infinite );
    }
    

    I’ve set the period to Timeout.Infinte so the timer doesn’t repeat. This means pollInterval is the time between one poll finishing and another starting – which will be different to the poll period if DoPoll() takes some time.

    Doing it this way also prevents the timer ticking again while a previous poll is still running.


    You can use the same principal to send the commands, but you will have to manage the current index into the sequencesList:

    var seqTimer = new Timer( HandleSequence, null, 0, Timeout.Infinate );
    int seqIndex = 0;
    ...
    
    void HandleSequence( object state )
    {
      var opcode = sequencesList[sequenceName][ seqIndex ];
    
      byte register = opcode.register;
      bool bit = opcode.bit;
      int duration = opcode.duration;
    
      lock( gate )
      {
        SetRegister(register, bit, false);
      }
    
      seqIndex++;
      if ( seqIndex < sequencesList[sequenceName].Count )
      {
        seqTimer.Change( duration, Timeout.Infinte );
      }
    }
    

    Or something along those lines ( but with suitable error handling! )

    You can handle termination and cancellation by just disposing the timers.


    BTW, there is an excellent ( and free ) ebook about threading that you could read:

    Albahari: Threading in C#

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
Basically, what I'm trying to create is a page of div tags, each has
I am using JSon response to parse title,date content and thumbnail images and place
I've got a string that has curly quotes in it. I'd like to replace
I have a small JavaScript validation script that validates inputs based on Regex. I
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I am using the SimpleRSS gem to parse a WordPress RSS feed. The only

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.