C#中如何处理线程

发布于 2024-12-11 22:23:59 字数 626 浏览 0 评论 0原文

我在我的网络应用程序中使用了线程,我在下面提到过:

var t1 = new Thread(F1);
            t1.IsBackground = true;
            t1.Start();

            var t2 = new Thread(F2);
            t2.IsBackground = true;
            t2.Start();

            var t3 = new Thread(F3);
            t3.IsBackground = true;
            t3.Start();

            var t4 = new Thread(F4);
            t4.IsBackground = true;
            t4.Start();


            t1.Join();
            t2.Join();
            t3.Join();
            t4.Join();

这工作正常并给了我所需的输出。

之后我是否需要杀死/处置线程,如果是,那么如何? 请指导。

我已经说过,如果我不处理它,可能会引发性能问题。

I have used threading in my web application which I have mentioned below:

var t1 = new Thread(F1);
            t1.IsBackground = true;
            t1.Start();

            var t2 = new Thread(F2);
            t2.IsBackground = true;
            t2.Start();

            var t3 = new Thread(F3);
            t3.IsBackground = true;
            t3.Start();

            var t4 = new Thread(F4);
            t4.IsBackground = true;
            t4.Start();


            t1.Join();
            t2.Join();
            t3.Join();
            t4.Join();

This is working fine and giving me the desired output.

Do I need to kill/Dispose the thread after this, if yes then how ?
Please guide.

I have told that if I do not dispose it, it might raise performance issue.

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

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

发布评论

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

评论(2

梦里南柯 2024-12-18 22:23:59

Join() 的调用会取消线程分配。您无需执行任何其他操作。只需确保线程在退出之前清理它们可能正在使用的所有资源即可。

也就是说,我强烈建议您考虑使用线程池或任务并行库 (TPL),而不是显式管理线程。它们更容易使用,处理这类事情也更顺利。

The call to Join() is what de-allocates the thread. You don't have to do anything else. Just make sure that the threads clean up any resources they might be using before they exit.

That said, I would urge you to look into using the thread pool or the Task Parallel Library (TPL) rather than explicitly managing threads. They're easier to use, and handle this kind of thing much more smoothly.

盛装女皇 2024-12-18 22:23:59

如果我处于你的位置,我会使用线程池而不是手动线程。它自己处理所有这些事情,并且您没有创建和销毁线程的开销。代码可能会稍微复杂一些,因为您需要使用 ManualResetEvent 而不是简单的 Thread.Join() (请参阅 如何完成 ThreadPool.Join?),但您不必担心创建太多线程,而且速度快了近 40 倍。

这是我编写的比较两种方法的测试类:

class ThreadPoolVsThreads
{
    private static readonly PerformanceMonitor threadPoolTest = new PerformanceMonitor("ThreadPoolTest");
    private static readonly PerformanceMonitor threadTest = new PerformanceMonitor("ThreadTest");

    private const int iterations = 100;
    private const int threads = 10;
    private static long somevalue;

    public static void Test()
    {
        TestHelper.PerformTest(10, threadPoolTest, ThreadPoolTest);
        TestHelper.PerformTest(10, threadTest, ThreadTest);
    }

    private static void ThreadPoolTest(int iteration)
    {
        for (int i = 0; i < iterations; i++)
        {
            var resetEvents = new ManualResetEvent[threads];
            for (int j = 0; j < threads; j++)
            {
                var re = new ManualResetEvent(false);
                resetEvents[j] = re;
                ThreadPool.QueueUserWorkItem(o =>
                {
                    somevalue++;
                    re.Set();
                });
            }
            WaitHandle.WaitAll(resetEvents);
        }
    }

    private static void ThreadTest(int iteration)
    {
        for (int i = 0; i < iterations; i++)
        {
            var threadArray = new Thread[threads];
            for (int j = 0; j < threads; j++)
            {
                var thread = new Thread(o => somevalue++);
                threadArray[j] = thread;
                thread.Start();
            }
            for (int j = 0; j < threads; j++)
            {
                threadArray[j].Join();
            }
        }
    }
}

这是五次运行的输出:

ThreadPoolTest 操作已完成:迭代 = 1,完成时间 = 53,平均完成时间 = 53.000

ThreadTest 操作已完成:迭代 = 1,完成时间 = 2128,平均完成时间 = 2128.000

ThreadPoolTest 操作已完成:迭代 = 2,完成时间 = 42,平均完成时间 = 47.500

ThreadTest 操作已完成:迭代 = 2,完成时间 = 2149,平均完成时间 = 2138.500

ThreadPoolTest 操作已完成:迭代 = 3,完成时间 = 65,平均完成时间 = 53.333

ThreadTest 操作已完成:迭代 = 3,完成时间 = 2078,平均完成时间 = 2118.333

ThreadPoolTest 操作已完成:迭代 = 4,完成时间 = 72,平均完成时间 = 58.000

ThreadTest 操作已完成:迭代 = 4,完成时间 = 2137,平均完成时间 = 2123.000

ThreadPoolTest 操作已完成:迭代 = 5,完成时间 = 43,平均完成时间 = 55.000

ThreadTest 操作已完成:迭代 = 5,完成时间 = 2085,平均完成时间 = 2115.400

If I were in your shoes, I'd be using a ThreadPool instead of manual threads. It handles all that stuff itself, and you don't have the overhead of creating and destroying threads. The code will probably be slightly more complex, because you'll need to use a ManualResetEvent instead of a simple Thread.Join() (see How can I accomplish ThreadPool.Join?), but you won't have to worry about creating too many threads, and it's nearly 40x faster.

Here's the class for a test I wrote comparing the two approaches:

class ThreadPoolVsThreads
{
    private static readonly PerformanceMonitor threadPoolTest = new PerformanceMonitor("ThreadPoolTest");
    private static readonly PerformanceMonitor threadTest = new PerformanceMonitor("ThreadTest");

    private const int iterations = 100;
    private const int threads = 10;
    private static long somevalue;

    public static void Test()
    {
        TestHelper.PerformTest(10, threadPoolTest, ThreadPoolTest);
        TestHelper.PerformTest(10, threadTest, ThreadTest);
    }

    private static void ThreadPoolTest(int iteration)
    {
        for (int i = 0; i < iterations; i++)
        {
            var resetEvents = new ManualResetEvent[threads];
            for (int j = 0; j < threads; j++)
            {
                var re = new ManualResetEvent(false);
                resetEvents[j] = re;
                ThreadPool.QueueUserWorkItem(o =>
                {
                    somevalue++;
                    re.Set();
                });
            }
            WaitHandle.WaitAll(resetEvents);
        }
    }

    private static void ThreadTest(int iteration)
    {
        for (int i = 0; i < iterations; i++)
        {
            var threadArray = new Thread[threads];
            for (int j = 0; j < threads; j++)
            {
                var thread = new Thread(o => somevalue++);
                threadArray[j] = thread;
                thread.Start();
            }
            for (int j = 0; j < threads; j++)
            {
                threadArray[j].Join();
            }
        }
    }
}

And here's the output for five runs:

ThreadPoolTest action completed: iteration = 1, completionTime = 53, averageCompletionTime = 53.000

ThreadTest action completed: iteration = 1, completionTime = 2128, averageCompletionTime = 2128.000

ThreadPoolTest action completed: iteration = 2, completionTime = 42, averageCompletionTime = 47.500

ThreadTest action completed: iteration = 2, completionTime = 2149, averageCompletionTime = 2138.500

ThreadPoolTest action completed: iteration = 3, completionTime = 65, averageCompletionTime = 53.333

ThreadTest action completed: iteration = 3, completionTime = 2078, averageCompletionTime = 2118.333

ThreadPoolTest action completed: iteration = 4, completionTime = 72, averageCompletionTime = 58.000

ThreadTest action completed: iteration = 4, completionTime = 2137, averageCompletionTime = 2123.000

ThreadPoolTest action completed: iteration = 5, completionTime = 43, averageCompletionTime = 55.000

ThreadTest action completed: iteration = 5, completionTime = 2085, averageCompletionTime = 2115.400

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