[英]Help regarding C# thread pool
我有一个经常被调用的方法,其中文本作为参数进入。
我正在寻找创建一个线程池,该线程池检查文本行并基于该行执行操作。
有人可以帮我了解创建线程池和触发新线程背后的基础知识吗? 这真是令人困惑。
您无需创建线程池。 只需使用由.NET管理的现有线程池。 要在线程池线程上执行函数Foo(),请执行以下操作:
ThreadPool.QueueUserWorkItem(r => Foo());
全部做完!
确保在Foo()函数中捕获异常-如果异常逃逸了Foo函数,它将终止进程。
这是一个简单的示例,可以帮助您入门。
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.
}
}
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.