简体   繁体   English

重用线程以执行不同的操作

[英]Reuse thread for different action

What is the proper way of reusing threads in .net? 在.net中重用线程的正确方法是什么? I know the threadpool does it but I'm not sure how. 我知道线程池是这样做的,但是我不确定如何做。 I already have server code with a lot (100+) threads working just fine but at the moment I have a new scenario where i need to reuse threads not for the same action but for a different one. 我已经拥有服务器代码,其中有很多(100+)个线程都可以正常工作,但是目前,我有一个新的场景,我需要重用线程而不是执行相同的操作,而要重用不同的线程。

If I have 2 methods, how do I reuse a thread mapped to method one and map it to run method 2 instead? 如果我有2种方法,如何重用映射到方法1的线程并将其映射到运行方法2?

Pseudo code: 伪代码:

 var thread = new Thread(method1);
 do work with thread here
 done, now how do i reuse the thread but tell it which method to run without creating a new one?

Note that I'm not looking for suggestions about how to accomplish this without using threads, I do need to use threads directly, neither the threadpool nor the task systems fits my use case at all (not willing to debate it here). 请注意,我并不是在寻找有关不使用线程就如何完成此操作的建议,我确实需要直接使用线程,线程池和任务系统都根本不适合我的用例(不愿在这里讨论)。 I'm just not sure about how to cleanly recycle a thread and map it to another function for a new run 我只是不确定如何干净地回收线程并将其映射到另一个函数以进行新的运行

You simply write a method that does one unit of work, and then when finished, goes and does another. 您只需编写一个执行一个工作单元的方法,然后在完成时执行另一个工作即可。 As far as Thread as concerned, it's just running it's one delegate, like it always does. Thread而言,它就像过去一样只运行一个委托。 That the delegate run happens to do two (or more, as it can keep finding work to do) logically separate operations in your program is something it doesn't know (or care) about. 委托运行恰好在程序中执行了两个(或更多,因为它可以继续寻找工作要做)在逻辑上是分开的操作,这是不知道(或不在乎)的。

A common situation, which is more or less what the thread pool does, is to have a queue of "things to do" and threads that just have a loop that, in the body of the loop, pulls an item from the queue and processes it. 一种常见的情况(或多或少是线程池的工作方式)是有一个“要做的事情”队列,而线程只有一个循环,该循环在循环体内从队列中拉出一个项并进行处理它。 (Just make sure to properly synchronize the data shared between threads here.) (只需确保在此处正确同步线程之间共享的数据即可。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM