views:

123

answers:

3

I have a method that gets called quite often, with text coming in as a parameter..

I'm looking at creating a thread pool that checks the line of text, and performs actions based on that..

Can someone help me out with the basics behind creating the thread pool and firing off new threads please? This is so damn confusing..

+3  A: 

I would suggest you read Threading in C# - Free ebook, specifically the Thread Pooling section

Mitch Wheat
+1  A: 

You don't need to create a thread pool. Just use the existing thread pool that is managed by .NET. To execute a function Foo() on a threadpool thread, do this:

ThreadPool.QueueUserWorkItem(r => Foo());

All done!

Be sure to trap exceptions in your Foo() function - if an exception escapes your Foo function, it will terminate the process.

dthorpe
+1  A: 

Here is a simple example that should get you started.

public void DoSomethingWithText(string text)
{
    if (string.IsNullOrEmpty(text))
        throw new ArgumentException("Cannot be null or empty.", "text");

    ThreadPool.QueueUserWorkItem(o => // Lambda
        {
            try
            {
                // text is captured in a closure so you can manipulate it.

                var length = text.Length; 

                // Do something else with text ...
            }
            catch (Exception ex)
            {
                // You probably want to handle this somehow.
            }
        }
    );
}
ChaosPandion