Thread.IsBackground抛出ThreadStateException

Ksi*_*ice 0 c# multithreading thread-exceptions

下一段代码抛出一个ThreadStateException:

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

并设置IsBackground属性

this.listeningThread.IsBackground = true;
Run Code Online (Sandbox Code Playgroud)

抛出异常.

怎么了?我在错误的地方使用IsBackground = true吗?

例外文字:

线程死了; 国家无法访问.
at System.Threading.Thread.SetBackgroundNative(Boolean isBackground
)
at My Systemspace.MyClass.StartListening()的System.Threading.Thread.set_IsBackgrounf(布尔值)
...

IsBackground属性仅在一个地方设置,此处.因此,它在线程工作期间永远不会改变.不幸的是我不能重现这个(仅在客户的系统上复制),所以我不知道原因.这就是我要问的原因.

ale*_*x.b 6

你收到错误的最主要原因是因为你设置this.listeningThread.IsBackground = true线程的那一刻已经死了.

让我解释:

 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;
Run Code Online (Sandbox Code Playgroud)

我不知道任务的完整上下文,但我认为将代码更改为:

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 }
}
Run Code Online (Sandbox Code Playgroud)