【问题标题】:C#.NET: does TransactionScope object synchronizes the access to code among multiple threads of users ?C#.NET:TransactionScope 对象是否在用户的多个线程之间同步对代码的访问?
【发布时间】:2013-09-10 15:21:57
【问题描述】:

TransactionScope 对象是否也在用户的多个线程之间同步对代码的访问?或者,它只将代码(业务操作)声明为原子(单个事务)?

详情: 1. 我正在为基础设施层中的存储库实现 UnitOfWork 类,它本身被定义为类库项目 (dll)。

  1. Repository 包含对 UnitOfWork 对象的引用,以调用其方法来维护已添加、更改或更新的实体的字典/集合。

  2. Unit of Work 类有一个成员函数 Commits(),它的代码封装在 TransactionScope 对象中。

考虑到多个用户访问域/业务对象,那么我假设每个用户都将在其线程中运行自己的一组业务对象。

我不确定在这种情况下 TransactionScope 对象会做什么?是否只是将用户线程内的多个操作标记为单个业务事务?或者它也在用户/s的不同线程之间同步对代码的访问? UnitOfWork 类的代码如下:

public class UnitOfWork
{
    private Dictionary<EntityBase, IUnitOfWorkRepository> addedEntities;
    private Dictionary<EntityBase, IUnitOfWorkRepository> changedEntities;
    private Dictionary<EntityBase, IUnitOfWorkRepository> deletedEntities;

    public UnitOfWork()
    {
        this.addedEntities = new Dictionary<EntityBase, IUnitOfWorkRepository>();
        this.changedEntities = new Dictionary<EntityBase, IUnitOfWorkRepository>();
        this.deletedEntities = new Dictionary<EntityBase, IUnitOfWorkRepository>();
    }

    #region IUnitOfWork Members

    public void RegisterAdded(EntityBase entity, IUnitOfWorkRepository repository)
    {
        this.addedEntities.Add(entity, repository);
    }

    public void RegisterChanged(EntityBase entity, IUnitOfWorkRepository repository)
    {
        this.changedEntities.Add(entity, repository);
    }

    public void RegisterRemoved(EntityBase entity, IUnitOfWorkRepository repository)
    {
        this.deletedEntities.Add(entity, repository);
    }

    public void Commit()
    {
        using (TransactionScope scope = new TransactionScope())
        {
            foreach (EntityBase entity in this.deletedEntities.Keys)
            {
                this.deletedEntities[entity].PersistDeletedItem(entity);
            }

            foreach (EntityBase entity in this.addedEntities.Keys)
            {
                this.addedEntities[entity].PersistDeletedItem(entity);
            }

            foreach (EntityBase entity in this.changedEntities.Keys)
            {
                this.changedEntities[entity].PersistDeletedItem(entity);
            }

            scope.Complete();
        }

        this.deletedEntities.Clear();

        this.addedEntities.Clear();

        this.changedEntities.Clear();
    }
    #endregion
}

【问题讨论】:

  • TransactionScope 类是线程安全的

标签: c# transactionscope unitofworkapplication


【解决方案1】:
  1. 在示例标题 P11 下的此链接中也回答了我的问题:http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners

  2. 问这个问题的原因只是为了确认接口上的面向对象规则,该规则在关于领域驱动设计书的讨论中陈述,其中 Repositoary Factory 类返回 IRepository 的通用类型,这也意味着 RepositoryFactory 将除了实现它之外,还能够返回 IRepository 或扩展 IRepository 的任何接口或类(这就是我认为 .NET 泛型的解释方式(完整代码和讨论如下)。

---讨论从这里开始---

--代码

using System;
using System.Collections.Generic;
using SmartCA.Infrastructure;
using SmartCA.Infrastructure.DomainBase;
using SmartCA.Infrastructure.RepositoryFramework.Configuration;
using System.Configuration;
namespace SmartCA.Infrastructure.RepositoryFramework
{
public static class RepositoryFactory
{
// Dictionary to enforce the singleton pattern
private static Dictionary < string, object > repositories = new
Dictionary < string, object > ();
/// < summary >
/// Gets or creates an instance of the requested interface. Once a
/// repository is created and initialized, it is cached, and all
/// future requests for the repository will come from the cache.
/// < /summary >
/// < typeparam name=”TRepository” > The interface of the repository
/// to create. < /typeparam >
/// < typeparam name=”TEntity” > The type of the EntityBase that the
/// repository is for. < /typeparam >
/// < returns > An instance of the interface requested. < /returns >
public static TRepository GetRepository < TRepository, TEntity > ()
where TRepository : class, IRepository < TEntity >
where TEntity : EntityBase
{
// Initialize the provider’s default value
TRepository repository = default(TRepository);
string interfaceShortName = typeof(TRepository).Name;
// See if the provider was already created and is in the cache
if (!RepositoryFactory.repositories.ContainsKey(interfaceShortName))
{
// Not there, so create it
// Get the repositoryMappingsConfiguration config section
RepositorySettings settings =
(RepositorySettings)ConfigurationManager.GetSection(RepositoryMappingConstants
.RepositoryMappingsConfigurationSectionName);
// Create the repository, and cast it to the interface specified
repository =
Activator.CreateInstance(Type.GetType(settings.RepositoryMappings[interfaceShortName]
.RepositoryFullTypeName)) as TRepository;
// Add the new provider instance to the cache
RepositoryFactory.repositories.Add(interfaceShortName, repository);
}
else
{
// The provider was in the cache, so retrieve it
repository =
(TRepository)RepositoryFactory.repositories[interfaceShortName];
}
return repository;
}
}
}

--代码

这个方法的签名很有趣,因为它使用了两个通用类型参数, TRepository 和 TEntity ,限制 TRepository 是一个类并实现 IRepository 接口,并且 TEntity 派生自 EntityBase 类。因为 Repository Framework 支持的接口不只是 IRepository ,所以该方法不能只返回 Repository 实例的 IRepository 类型。它还必须支持返回任何实现 IRepository 的接口,因为正在使用的存储库接口也可以在其中定义其他方法;这就是为什么将 TRepository 声明为 Generic 类型,以便工厂可以支持 Repository Framework 要求能够传入有效的 Repository 接口类型并获取接口的实例(只要它已在应用程序的配置文件中正确定义)。

---讨论到此结束---

【讨论】:

    【解决方案2】:

    @Adil Mughal:非常感谢,您的及时回答真的很有帮助。有关 C#.NET 上下文中术语“线程安全”的更多详细信息,我还获得了一些有用的链接,并希望在下面分享:(由此我得到的是 TransactionScope 对象是“线程安全的”,这意味着TransactionScope 对象块中的任何代码都由 .NET 很好地同步,并且访问代码块的多个线程不会产生并发问题,例如它会锁定代码块)

    What "thread safe" really means...In Practical terms

    What Makes a Method Thread-safe? What are the rules?

    Thread safe collections in .NET

    http://www.codeproject.com/Articles/37976/Writing-Thread-Safe-Code-in-C

    http://www.albahari.com/threading/part2.aspx

    问候, 法哈尔·安瓦尔

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多