C
C#4mo ago
ChezZ

Creating a thread that lives for as long as the application.

I wrote a server using a c library, I created two threads using
new Thread
new Thread
and have an infinite loop running in the threads method. One thread handles all socket related code, and adds incoming packets to be deserialized to a single producer single consumer queue. The other thread deserializes the packets. The codes works but it has a flaw. Creating the thread via
new Thread
new Thread
fails and I get an exception if the system running the app has no more threads available. is it possible to tell the app use an existing thread if creating a new one fails:
thread = new Thread(DoWork); //this line of code throws the exception if the cpu runs out of threads
thread.IsBackground = true;
shouldRun = true;

private void DoWork()
{

Init();
while (shouldRun == true)
{
Consume();
Tick();

}
}
thread = new Thread(DoWork); //this line of code throws the exception if the cpu runs out of threads
thread.IsBackground = true;
shouldRun = true;

private void DoWork()
{

Init();
while (shouldRun == true)
{
Consume();
Tick();

}
}
9 Replies
jcotton42
jcotton424mo ago
uh, if the OS has run out of threads, there's nothing you can do that being said, you probably want to use tasks, not an explicit thread
ChezZ
ChezZOP4mo ago
aren't tasks just meant for one time operations? The threads live for the life of the application.
jcotton42
jcotton424mo ago
eh, yes and no but, socket stuff is async anyhow so you'll be awaiting a lot
ChezZ
ChezZOP4mo ago
im not using c# sockets its using a c library no awaiting
jcotton42
jcotton424mo ago
oh
canton7
canton74mo ago
What exactly is the text of the exception? There's no hard limit on the number of threads (at least in Windows). It doesn't "run out" of threads. It can run out of memory to use as stack space for threads, but that'll happen at many hundreds of thousands
ChezZ
ChezZOP4mo ago
each app calls new thread twice, after exactly 4 instances of my app is running the 5th will get null reference exceptions when calling thread.Start cause var thread = new Thread returns null
jcotton42
jcotton424mo ago
The OS can support thousands of threads. Something is wrong.
ChezZ
ChezZOP4mo ago
hmm let me try something ok prior to calling thread.start my custom pool allocator was failing to allocate the memory needed yeah my system runs out of memory after so many instances oops
Want results from more Discord servers?
Add your server