有关C#线程池的帮助

时间:2010-04-18 05:23:52

标签: c# multithreading threadpool

我有一个经常被调用的方法,文本作为参数进入..

我正在寻找创建一个检查文本行的线程池,并根据它执行操作。

有人可以帮我解决创建线程池和启动新线程的基础知识吗?这真令人困惑......

3 个答案:

答案 0 :(得分:3)

我建议你阅读Threading in C# - Free ebook,特别是Thread Pooling部分

答案 1 :(得分:1)

您无需创建线程池。只需使用.NET管理的现有线程池即可。要在线程池线程上执行函数Foo(),请执行以下操作:

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

全部完成!

确保在Foo()函数中捕获异常 - 如果异常转义了Foo函数,它将终止该过程。

答案 2 :(得分:1)

这是一个简单的示例,可以帮助您入门。

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.
            }
        }
    );
}
相关问题