线程在 IIS 上托管的 WCF 应用程序内随机停止

Thread stops randomly inside WCF application hosted on IIS

根据客户要求,我实现了一个 C# WCF Web 服务,该服务在每次调用时启动一个执行其自身异步处理的线程。线程启动后,Web 服务正常结束执行,与线程处理状态无关。

我遇到的问题是,有时,并非总是,线程会无一例外地随机中断。中断发生在不同的时间点和不同的时间,所以我无法确定其故障的常数。

我报了启动线程的服务的那段代码

//WCF starts
....
//Starts a new thread
System.Threading.ThreadPool.QueueUserWorkItem(th =>
{

    ThreadContext.Properties["property1"] = prop1;

    // The class to be executed by the thread
    ExecutionClass executionClass= new ExecutionClass();

    Logger.log("start elaboration");       

    executionClass.start(parameter);
});
....
// the WCF returns the response independently of thread execution
return response;

可能是 windows 或 IIS 导致线程结束?我可以做些什么来解决这个问题吗?

P.S。 我知道这不是一个好的解决方案,但要求是客户提出的。

查看您站点的应用程序池(在 IIS 中)。有许多设置会影响线程的生命周期。

您的代码没有启动新的 Thread。它确实启动了一个新的 unit-of-work,因此 ThreadPool 可以 运行 你在已经创建的线程中工作。
如果您开始 Task 而不是 UserWorkItem,您的客户会满意吗?您可以 运行 它默认为 ThreadPool,因此您的应用程序的行为将完全相同,但您可以轻松地附加到异常处理任务的延续,因此您将始终了解代码中未完成的任务。 您甚至可以为 ThreadPool 提供一个标志,表明此任务将是一个很长的 运行ning 任务,因此这将减少线程的杀戮。

Run method

Task.Factory.Run(() =>
{
    ThreadContext.Properties["property1"] = prop1;

    // The class to be executed by the thread
    ExecutionClass executionClass= new ExecutionClass();

    Logger.log("start elaboration");       

    executionClass.start(parameter);
// TaskScheduler.Default is used by default to run your code in ThreadPool
})
// handle the thread aborting appropriately
.ContinueWith(t =>  
  HandleException(task.Exception),
  // no code if task is success or canceled
  TaskContinuationOptions.OnlyOnFaulted);

with StartNew method with LongRunning 参数:

Task.Factory.StartNew(() =>
{
    ThreadContext.Properties["property1"] = prop1;

    // The class to be executed by the thread
    ExecutionClass executionClass= new ExecutionClass();

    Logger.log("start elaboration");       

    executionClass.start(parameter);

}
// as you don't interested in the task's future, you don't need any cancellation token
, CancellationToken.None
// provide the long running parameter
, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning
// provide TaskScheduler.Default to run your code in the ThreadPool
, TaskScheduler.Default);)
// handle the thread aborting appropriately
.ContinueWith(t =>  
  HandleException(task.Exception),
  // no code if task is success or canceled
  TaskContinuationOptions.OnlyOnFaulted);

相关链接:

感谢大家的建议!

终于找到了问题的原因:当我的 Web 服务调用其他 Web 服务时,如果它等待答案的时间太长,线程就会被 IIS 杀死。

我的原因是系统工程师在 IIS 上设置了一个超时值,目的是在应用程序处于等待状态超过 120 秒时释放内存。

不幸的是他们不能改变这个值,但现在我有问题的证据所以我现在可以自由地改变架构。