Practice Threading with Polling

I have a C # application that needs to be constantly read from a program; sometimes there is a chance that it doesn't find what it needs, which will throw an exception. This is a limitation of the program that it must read.

This often causes the program to block when it tries to poll. So I solved it by creating a "poll" in a separate thread. However, by watching the debugger, the thread is created and destroyed every time. I'm not sure if this is typical or not; but my question is, is this good practice or am I using streams for the wrong purpose?

ProgramReader
{ 
  static Thread oThread;
  public static void Read( Program program )
  {
    // check to see if the program exists
    if ( false )
      oThread = new ThreadStart(program.Poll);
    if(oThread != null || !oThread.IsAlive )
      oThread.Start();
  }
}

      

This is my general pseudocode. It runs every 10 seconds or so. Is this a huge success? The operation he performs is relatively small and easy; just repetitive.

+2


a source to share


2 answers


A Thread

cannot be restarted, so you see what you see in the debugger. This is normal behavior, but I'm worried about two problems here:

  • You say specifically that Program

    it will sometimes throw an exception, but you never catch it. Unhandled exceptions on a background thread bring down your whole process.

  • You create threads regardless of the circumstances. It is not clear if it Program.Poll

    is really thread safe (my guess is missing), and even if it is, you might not want to flood the system with these requests.

A better design might be something like:

private AutoResetEvent polledEvent = new AutoResetEvent(true);

public void Read(Program program)
{
    polledEvent.WaitOne();
    ThreadPool.QueueUserWorkItem(s => 
    {
        try
        {
            program.Poll();
        }
        catch (PollingException ex)
        {
            // Handle the exception
        }
        polledEvent.Set();
    });
}

      



This will solve both of these problems by handling any exceptions, and will also reduce the number of polling requests that can occur simultaneously. It also reuses streams with ThreadPool

.

If the method is Poll

indeed thread safe and you are fine with multiple successive requests, change AutoResetEvent

to Semaphore

and initialize it with the actual number of requests you want to execute simultaneously.

One final note: if this is happening in a Windows Forms, Windows Service, or WPF application, I would recommend using the BackgroundWorker

native flow code instead of rolling. Most of the work is already done for you there, you just need to write your polling loop inside the event handler DoWork

.

+4


a source


Either create a thread that waits and sleeps, or use a ThreadPool, which sounds like a thing to do for your task.



0


a source







All Articles