Multithreading WCF wsHttpBinding与IIS

Multithreading WCF wsHttpBinding与IIS,multithreading,wcf,iis,Multithreading,Wcf,Iis,我使用wsHttpBinding和IIS设置了一组WCF服务,并实现了自定义安全性(使用消息头)来确定发出请求的用户。根据我几年的netTcpBinding经验(使用Windows服务托管,而不是IIS),我一直认为WCF端点接收到的每个请求都会在一个新线程上结束。使用此假设,我的自定义安全类(实现IDispatchMessageInspector)基于在消息头中查找“令牌”(Guid)来设置线程标识,如下所示: public object AfterReceiveRequest(ref Sys

我使用wsHttpBinding和IIS设置了一组WCF服务,并实现了自定义安全性(使用消息头)来确定发出请求的用户。根据我几年的netTcpBinding经验(使用Windows服务托管,而不是IIS),我一直认为WCF端点接收到的每个请求都会在一个新线程上结束。使用此假设,我的自定义安全类(实现IDispatchMessageInspector)基于在消息头中查找“令牌”(Guid)来设置线程标识,如下所示:

public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
{
     string token = string.Empty;
     if (request.Headers.FindHeader("SecurityToken", Primitives.SerializationNamespace) > -1)
         token = request.Headers.GetHeader<string>("SecurityToken", Primitives.SerializationNamespace);

     if (!string.IsNullOrEmpty(token))
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(token, "AppName"), new string[] { "testrole" });
    else
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("guest", "AppName"), new string[] { });
     }

     return null;
 }
我还尝试使用以下属性标记我的所有服务实现(直接位于.svc文件后面),但这没有改变任何内容:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

关于如何保证每个请求都在一个新线程上,有什么想法吗?或者,有没有更好的方法来存储/确定发出请求的用户是谁,而不存在任何可能的重叠?

在您无法控制线程的环境中使用
ThreadStatic
变量将导致灾难。WCF(IIS和自托管)和ASP.NET都在内部使用线程池=每个请求都由单独的线程提供服务,但这些线程会被重新用于后续请求,因此无法避免


使用自定义
OperationContext
来存储用户,而不是
ThreadStatic
变量。

我想这正是我需要的。我会再测试一点,但它看起来工作得很好。谢谢你到底为什么要玩
ThreadStatic
?你想完成什么?
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]