Threads problem

R

RahimAsif

Hi guys,
I would like some advice on thread programming using C# so I wanted
some advice.

I am writing an application that communicates with a panel over
ethernet, collects data and writes it to a file. The way the data is
collected is that we have different schedules (so one set of data is
collected say every second, another set of data might be collected
every 30 seconds, and so on).

The way I am approaching this is that I have created a class called
Scheduler, which consists of an ArrayList which has the individual
schedules. Each individual schedule has a timer object which would fire
after a specified amount of time (again this would be different for
each different schedule). When it fires, it would set a flag. In the
scheduler I have a function called Run, which goes through each
individual schedule item and see if the flag is set. If it is, it would
call a method in the individual schedule (called DoServicing()) and
clear the flag. The DoServicing() method calls the communication
function and then writes the flag.

Now I am creating the scheduler on a separate thread when the user
presses a Start button, and the scheduler just keeps calling Run()
forever, until the user presses a stop button. The problem I am running
into is that it seems like when the scheduler is in the DoServicing()
method (on its own thread), often times the application would switch
threads (back to the main UI thread). So whats happening is that the
file is not getting written. At other times, if there are 2
communication messages in DoServicing() its doing only 1 before
switching threads back to the main UI thread. Interestingly enough, if
I had no communication messages (just writing to file) everything works
perfectly according to the given schedule. As soon as I put the
communication messages in the DoServicing() method, it seems to switch
threads before going through the whole method.

In this sort of application, where the data must be collected and
written exactly at user specified intervals, obviously I need more
control on the thread on which the scheduler is running. What I would
like is that the scheduler should be continuously running according to
the given individual schedules (communicating to the panel and writing
the files). How do I achieve that?

Note: I have already tried lock around the entire body of the
DoServicing() method, as well as setting the thread priority of the
scheduler thread to highest. Neither of them worked.
 
D

Dmytro Lapshyn [MVP]

Hi,

I'd have one System.Threading.Timer instance that would go through the
schedules every second and fire off tasks due now on the thread pool (see
System.Threading.ThreadPool).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top