C# 线程在IIS上托管的WCF应用程序内随机停止
根据客户需求,我实现了一个C#WCF web服务,该服务在每次调用时启动一个线程,该线程自己执行异步处理。一旦线程启动,web服务将正常结束其执行,而不管线程处理的状态如何 我遇到的问题是,有时(并非总是)线程会毫无例外地随机中断。中断发生在不同的点和不同的时间,因此我无法识别其故障中的常数 我报告启动线程的服务的代码片段C# 线程在IIS上托管的WCF应用程序内随机停止,c#,multithreading,wcf,iis,C#,Multithreading,Wcf,Iis,根据客户需求,我实现了一个C#WCF web服务,该服务在每次调用时启动一个线程,该线程自己执行异步处理。一旦线程启动,web服务将正常结束其执行,而不管线程处理的状态如何 我遇到的问题是,有时(并非总是)线程会毫无例外地随机中断。中断发生在不同的点和不同的时间,因此我无法识别其故障中的常数 我报告启动线程的服务的代码片段 //WCF starts .... //Starts a new thread System.Threading.ThreadPool.QueueUserWorkItem(t
//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导致线程结束?我能做点什么来解决这个问题吗
附言。
我知道这不是一个很好的解决方案,但这些要求是由客户端强加的。查看您站点的应用程序池(在IIS中)。有许多设置会影响线程的生存期。您的代码不会启动新的
线程。它确实启动了一个新的工作单元
,因此线程池可以在已经创建的线程中运行您的工作。
如果您启动任务而不是用户工作项
,您的客户会满意吗?您可以在默认的线程池中运行它,因此应用程序的行为将完全相同,但您可以轻松地附加到任务的继续部分以进行异常处理,因此您将始终了解代码中未完成的任务。
您甚至可以为ThreadPool
提供一个标志,表明此任务将是一个长期运行的任务,因此这将减少线程的死亡
与
带长时间运行
参数:
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秒时释放内存
不幸的是,他们无法更改该值,但现在我有了问题的证据,因此我现在可以自由更改架构。当回收应用程序池时,肯定是IIS结束了线程,请检查应用程序pol设置并禁用自动重新启动。您有哪个版本的IIS?我将尝试第二个解决方案,然后回来!)
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);