有关 C# 线程池的帮助

发布于 2024-08-29 03:37:24 字数 120 浏览 4 评论 0原文

我有一个经常被调用的方法,其中文本作为参数传入。

我正在考虑创建一个线程池来检查文本行,并据此执行操作。

有人可以帮我解决这个问题吗?创建线程池和启动新线程背后的基础知识?这真是太令人困惑了..

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..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

够运 2024-09-05 03:37:24

我建议您阅读 Threading in C# - Free ebook,特别是 线程池 部分

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

与他有关 2024-09-05 03:37:24

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

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

全部完成!

请务必在 Foo() 函数中捕获异常 - 如果异常从 Foo 函数中逃脱,它将终止该进程。

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.

梦里寻她 2024-09-05 03:37:24

这是一个应该帮助您入门的简单示例。

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.
            }
        }
    );
}

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.
            }
        }
    );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文