lorenz albert
lorenz albert

Reputation: 1459

c# How to restructure my program for threading

The Problem

I have a constant flow of datapackages. Every time a new package is incoming (100 ms interval) an event pops in which I send the package to a class to process the data and visualize it. Unfortunately, it could happen that the process of a package is aborted if a new package was sent before the current one has been processed.

What I have now

Is a Code that is used as dll for another program. When I started coding the dll, I was new to c# so I didn't want to do it too complicated. Everything is working but I faced some ugly Frame skips (in my visualization part) if the cpu is very busy.

I have several classes and one of them is handling all packages. This class has round about 50 attributes 25 functions and 1000 lines of code. only 6 functions are needed for the calculations. The rest is setting the attributes correctly (if the user changes settings).

What I need to change

So now I want to buffer all incoming data by using a List. The list should be handled by another thread. So it is very unlikely that writing the data to the list takes longer than 100 ms ^^ (2 arrays with ca. 40 elements each that should be equal to nothing)

What I have in mind

Splitting the mentioned class into 2 separate classes. One that handles the packages and one that handles the settings. So I would split the user and the "program" input. Creating a thread that uses the "package handling" class to process the buffered data.

What I have no clue about

Since the settings class contains important attributes that are needed by the handling class I don't know how to do it best, because The handling class also needs to change/fill buffers in the settings class. But this one will be invoked by the main thread. Or is it better to not split the setting and handling class and leave it as it is? I am not so familiar with threading and read the first chapter of this free e-book Threading in C#

Upvotes: 4

Views: 183

Answers (1)

IvoTops
IvoTops

Reputation: 3531

I would just add a queue and implement a thread for the processing. That will help you with the skips and requires little change. Refactoring the code by splitting settings apart seems like a lot of work with little benefit and possible new bugs.

To add the queue;

  • Create a ConcurrentQueue (this is threadsafe lifo, which is what you need)

        var cq=new ConcurrentQueue<Packets>();
    
  • Add all your datapackets to that Queue

         cq.Enqueue(newPacket);
    
  • Create another thread that loops around and processes the Queue

         if (cq.TryDequeue(out newPacket)) 
         { 
            // Visualize new packet
         }
    

Upvotes: 2

Related Questions