【问题标题】:Are extension classes in a mulitithreading WCF environment thread safe?多线程 WCF 环境中的扩展类是线程安全的吗?
【发布时间】:2013-12-23 11:04:52
【问题描述】:

当我突然发现另一个产品的详细信息最终出现在另一个产品中时,我有不同的产品异步运行。

当我将它传输到另一个服务时,我将它存储在 XML 中。

运行时间:

var transactionScopeOptions = new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted, Timeout = Timeout = new TimeSpan(0, 10, 0) };
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionScopeOptions))
{
    using (var dataContext = new FooContext())
    {
        /* code goes here, single instance of dataContext per thread */
    }
}

使用扩展类(哪里出错):

public static class FooExtensions
{
    public static int GetID(this FooClass foo)
    {
        var result = foo != null ? foo.ID : 0;
        return result;
    }
}

如果这不是线程安全的,我如何使它成为线程安全的?

编辑:

也可能是发生了内存泄漏,但不确定。 使用 WCF ConcurrencyMode.MultipleInstanceContextMode.Single

【问题讨论】:

    标签: multithreading wcf thread-safety msmq


    【解决方案1】:

    扩展方法的线程安全性不亚于任何其他方法。它们只是普通静态方法之上的语法糖。实际上,您可以调用与FooExtensions.GetID(foo) 相同的方法,而不是执行foo.GetID(),它会执行相同的操作。这就是编译器真正为你做的事情。

    根据您提供的示例,您的扩展方法是线程安全的。您的问题更有可能是由于使用了IsolationLevel.ReadUncommittedReadUncommitted 可能导致脏读、不可重复读、相同数据被读两次和幻读。有关详细信息,请参阅this article。我建议您提高隔离级别,看看这是否能让您的问题消失。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多