C#中如何处理线程
我在我的网络应用程序中使用了线程,我在下面提到过:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对
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.
如果我处于你的位置,我会使用线程池而不是手动线程。它自己处理所有这些事情,并且您没有创建和销毁线程的开销。代码可能会稍微复杂一些,因为您需要使用 ManualResetEvent 而不是简单的 Thread.Join() (请参阅 如何完成 ThreadPool.Join?),但您不必担心创建太多线程,而且速度快了近 40 倍。
这是我编写的比较两种方法的测试类:
这是五次运行的输出:
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:
And here's the output for five runs: