简体   繁体   中英

Reuse thread for different action

What is the proper way of reusing threads in .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.

If I have 2 methods, how do I reuse a thread mapped to method one and map it to run method 2 instead?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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