6

I'm trying to convert some code from just creating a new thread to run a function to making it use a Thread Pool or even the Task Paralleling Library. I'm doing this since I know that despite the Worker Thread's Function may run indefinitely (in theory), each thread will spend most of it's time doing nothing. I also want something to minimize the overhead for the creation and destruction of the Worker Threads, as connections may timeout or new ones get created. That - and seeing CLRProfiler show 7836 threads were finalized in/after a 62 hour test run is a little unnerving, with a single (if finicky) device sending a message.

Here's what I want to do:

Main Thread.

1.) Have a TCPListener accept a TcpClient

2.) Fire off a Worker Thread which uses that TcpClient

3.) Go back to step 1 if we haven't been told to stop.

Worker Thread (To used in the Pool/Tasks)

1.) Check to see if we have a message from the TcpClient

2.) If so, parse message, send off to database, and sleep for 1 second.

3.) Otherwise, sleep for 1 millisecond.

4.) Go back to step 1 if we haven't been told to stop and have not timed out.

Here's the original approach:

private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
private static bool stop = false;

private void MainThread()
{
    TcpListener universalListener = new TcpListener(IPAddress.Any, currentSettings.ListeningPort);
    universalListener.Start();

    while (!stop)
    {
        IAsyncResult result = universalListener.BeginAcceptTcpClient(WorkerThread, universalListener);
        connectionWaitHandle.WaitOne();
        connectionWaitHandle.Reset();
    }
}

private void WorkerThread(IAsyncResult result)
{
    TcpListener listener = result.AsyncState as TcpListener;

    if (listener == null)
    {
        connectionWaitHandle.Set();
        return;
    }

    TcpClient client = listener.EndAcceptTcpClient(result);
    connectionWaitHandle.Set();

    NetworkStream netStream = null;

    bool timedout = false;

    try
    {
        while (!timedout && !stop)
        {
            if (client.Available > 0)
            {
                netStream = client.GetStream();

                //Get and Parse data here, no need to show this code
                //The absolute fastest a message can come in is 2 seconds, so we'll sleep for one second so we aren't checking when we don't have to.
                Thread.Sleep(1000);
            }
            else
            {
                //Sleep for a millisecond so we don't completely hog the computer's resources.
                Thread.Sleep(1);
            }

            if (/*has timed out*/)
            {
                timedout = true;
            }
        }
    }
    catch (Exception exception)
    {
        //Log Exception
    }
    finally
    {
        client.Close();
    }
}

I've tried replacing the universalListener.BeginAcceptTcpClient(...) et. all with

(new Task.TaskFactory.FromAsync<TCPClient>(universalListener.BeginAcceptTcpClient, universalListener.EndAcceptTcpClient, universalListener).ContinueWith(WorkerThread);

as well as removing the AutoResetEvent connectionWaitHandle code, but the Worker Thread seemed to only fire once.

I'm also a little unsure if I should even try to use a Thread Pool or a Task, as everything I could find about Thread Pools and Tasks (official documentation or otherwise) seems to indicate they should be used with threads that have an extremely short lifespan.

My questions are:

  1. Is the Thread Pool or even Tasks from the Task Parallel Library appropriate for Long-lived, but mostly wheel spinning, Threads?
  2. If so, how would I best implement the correct pattern?
  3. If so, did I have the right idea on using TaskFactory.FromAsync(...).ContinueWith(...)?

1 Answer 1

6

By default, the TPL will use the Thread Pool. So, either way you are using the Thread Pool. The question is just which programming model you use to access the pool. I strongly suggest TPL, as it provides a superior programming abstraction.

The threads in your example are actually not spinning (burning CPU cycles), but rather blocking on a wait handle. That is quite efficient and does not consume a thread while blocked.

UPDATE

The TaskFactory.FromAsync(...).ContinueWith(...) pattern is appropriate. For a great list of reasons, see this question.

If you are using C# 5 / .NET 4.5, you can use async/await to express your code pattern even more compactly.

http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2010/11/22/c-5-0-rise-of-the-task.aspx

5
  • Ok, so it would be a good idea to use TPL for this? I would like to re-iterate that a Worker Thread wouldn't stop after receiving a message, only after either the TCPClient times out or the program is told to stop. And is TaskFactory.FromAsync(Accept TCPClient).ContinueWith(Worker Thread) the right way to go?
    – Tory
    Nov 12, 2012 at 21:59
  • Ok, thank you for your answer. I'll give it another shot and have it run over night to see if it works properly.
    – Tory
    Nov 12, 2012 at 23:46
  • @Tory I also busy developing a communications server using the TPL and it seems to be working quite well. I just recently started using the async/await patterns in .NET 4.5 (still trying to get my head around it, but it looks very promising). We have not been in a position to do stress testing and we really hope at this time we would not need to much tweaking when it comes to that. I would love to know what your findings are in your tests. Nov 14, 2012 at 6:55
  • It seems to be working just fine. One of my biggest concerns was the massive creation and destruction of Threads (7836 for one finicky connection). Doing a minor stress test of 10 simulated finicky connections over night only produced 1691 (quite the improvement) as well as less Gen0 garbage collection than 10x (~30 vs 144). Though I did have to split it into Task<TcpClient> t = Task.Factory.FromAsync<TcpClient>(...); t.Wait(); t.ContinueWith(...); so the Factory wouldn't pump out a ton of tasks and thus crash the program from memory starvation.
    – Tory
    Nov 15, 2012 at 14:54
  • @Tory: The nice thing about the thread pools is that threads are not created and destroyed, but rather reused. True their state has to be re-initialized, but their stack memory allocation etc. is already setup.
    – Eric J.
    Nov 16, 2012 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.