本文介绍了在哪里存储当前 WCF 调用的数据?ThreadStatic 安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的服务执行时,许多类将需要访问 User.Current(即我自己的 User 类).我可以安全地将 _currentUser 存储在 [ThreadStatic] 变量中吗?WCF 是否重用其线程?如果是这样,它什么时候会清理 ThreadStatic 数据?如果使用 ThreadStatic 不安全,我应该把数据放在哪里?OperationContext.Current 中是否有可以存储此类数据的地方?

While my service executes, many classes will need to access User.Current (that is my own User class). Can I safely store _currentUser in a [ThreadStatic] variable? Does WCF reuse its threads? If that is the case, when will it clean-up the ThreadStatic data? If using ThreadStatic is not safe, where should I put that data? Is there a place inside OperationContext.Current where I can store that kind of data?

编辑 12/14/2009: 我可以断言使用 ThreadStatic 变量是不安全的.WCF 线程位于线程池中,并且永远不会重新初始化 ThreadStatic 变量.

Edit 12/14/2009: I can assert that using a ThreadStatic variable is not safe. WCF threads are in a thread pool and the ThreadStatic variable are never reinitialized.

推荐答案

有一个博客 post 建议实施 IExtension<T>.你也可以看看这个 讨论.

There's a blog post which suggests implementing an IExtension<T>. You may also take a look at this discussion.

这是一个建议的实现:

public class WcfOperationContext : IExtension<OperationContext>
{
    private readonly IDictionary<string, object> items;

    private WcfOperationContext()
    {
        items = new Dictionary<string, object>();
    }

    public IDictionary<string, object> Items
    {
        get { return items; }
    }

    public static WcfOperationContext Current
    {
        get
        {
            WcfOperationContext context = OperationContext.Current.Extensions.Find<WcfOperationContext>();
            if (context == null)
            {
                context = new WcfOperationContext();
                OperationContext.Current.Extensions.Add(context);
            }
            return context;
        }
    }

    public void Attach(OperationContext owner) { }
    public void Detach(OperationContext owner) { }
}

你可以这样使用:

WcfOperationContext.Current.Items["user"] = _currentUser;
var user = WcfOperationContext.Current.Items["user"] as MyUser;

这篇关于在哪里存储当前 WCF 调用的数据?ThreadStatic 安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:38