Thread.IsBackground throws ThreadStateException

2.4k Views Asked by At

Next piece of code throws a ThreadStateException:

public void StartListening()
{
     this.isListening = true;
     if (!this.listeningThread.IsAlive)
         this.listeningThread = new Thread(ListenForClients);
     this.listeningThread.Start();
     this.listeningThread.IsBackground = true;
}

And while setting the IsBackground property

this.listeningThread.IsBackground = true;

the exception is thrown.

What's wrong? Am I using IsBackground=true in the wrong place?

Exception text:

Thread is dead; state cannot be accessed.
at System.Threading.Thread.SetBackgroundNative(Boolean isBackground)
at System.Threading.Thread.set_IsBackgrounf(Boolean value)
at MyNamespace.MyClass.StartListening()
...

IsBackground property set up only in one place, here. So, it never changes during thread work. Unfortunately I can't reproduce this (reproduced on client's system only), so I don't know the reason. And that's why I'm asking.

1

There are 1 best solutions below

0
On BEST ANSWER

The most reason why you're getting the error is because at the moment you set this.listeningThread.IsBackground = true the thread is already dead.

Let me explain:

 this.isListening = true;
 if (!this.listeningThread.IsAlive)// thread is alive
     this.listeningThread = new Thread(ListenForClients);
 this.listeningThread.Start();// thread is alive, still ..
 // thread completes here
 // you might add some delay here to reproduce error more often
 this.listeningThread.IsBackground = true;

I don't know the full context of the task, but I think it makes sense to change code to:

public void StartListening()
{
 this.isListening = true;
 if (!this.listeningThread.IsAlive)
 {
     this.listeningThread = new Thread(ListenForClients);
     this.listeningThread.IsBackground = true;
     this.listeningThread.Start();
 }
 // else { do nothing as it's already alive }
}