Windows PowerShell 事务编程实战:基于 SupportsTransactions 与 CurrentPSTransaction 构建可回滚的 TransactedComment 示例

原创2026-10-14 21:07:551,886 阅读
文章标签:示例工程

Windows PowerShell 事务编程实战:基于 SupportsTransactions 与 CurrentPSTransaction 构建可回滚的 TransactedComment 示例

导读

本文以 Windows-classic-samples 仓库中 Samples/PowerShell/Transactions/Transactions01/README.md 为主体,完整讲解如何编写一组参与 Windows PowerShell 事务的 cmdlet:它们维护一个"评论日志",该日志可以随事务一起被提交、回滚或清除,并配套实现了一个存储字符串的轻量级 .NET 事务资源管理器。读完本文,你将掌握 SupportsTransactionsAttribute 的声明方式、CurrentPSTransaction 与 using 块在 cmdlet 内的正确用法,以及通过实现 IEnlistmentNotification 让自定义对象获得提交/回滚能力的完整套路,并能在本地 Visual Studio 中构建、加载并实际运行这套示例。

示例概览与核心学习目标

Transactions01 示例(源码位于 Samples/PowerShell/Transactions/Transactions01/cs/)由一组相互配合的组件组成:

  • 三个 cmdlet:Add-TransactedComment、Get-TransactedComment、Clear-TransactedComment,均声明支持事务;
  • 一个事务资源管理器:TransactedComment 类,负责在事务内暂存修改、在提交时固化、在回滚时丢弃;
  • 模块级隔离存储:评论数据保存在模块的 PrivateData 属性中,与运行空间(runspace)绑定。

原文档明确指出,本示例主要演示以下三点(这也是学习 Windows PowerShell 事务机制的三条主线):

  1. SupportsTransactionsAttribute(即 [Cmdlet(..., SupportsTransactions = true)])的用法;
  2. CurrentPSTransaction 的用法;
  3. 一个 .NET 事务资源管理器(transacted resource manager)的实现。

从 Readme.txt 可知,本示例提供 C# 语言实现;项目文件 TransactedComment.csproj 以库(OutputType 为 Library)形式输出,引用 System.Management.Automation(版本 3.0.0.0,对应 Windows PowerShell 3.0)与 system.transactions,可见其依赖 Windows PowerShell 3.0 及以上运行时。

环境要求

根据原文档的 "Operating system requirements" 一节,本示例的运行前提如下:

类别 要求
客户端(Client) Windows 8.1
服务器(Server) Windows Server 2012 R2

构建工具方面,需要 Microsoft Visual Studio(示例为 .NET Framework 4.0 目标框架、ToolsVersion="4.0" 的 C# 项目),运行环境则需要 Windows PowerShell(示例引用的是 PowerShell 3.0 程序集)。由于示例编译产物是一个程序集(assembly),它需要被放入 PowerShell 模块目录后通过 Import-Module 加载。

构建示例(Build the sample)

按原文档步骤操作即可完成构建:

  1. 启动 Microsoft Visual Studio,选择 File > Open > Project/Solution;
  2. 进入本示例所在目录 Samples/PowerShell/Transactions/Transactions01/cs,双击解决方案文件 TransactedComment.sln 打开项目;
  3. 按 F7 或使用 Build > Build Solution 构建。

构建完成后,程序集默认输出到项目的 bin 或 bin\Debug 目录。这一行为与 TransactedComment.csproj 中的 OutputPath 配置一致:Debug|AnyCPU 配置输出到 bin\Debug\,Release|AnyCPU 配置输出到 bin\Release\。生成的主程序集文件名为 TransactedComment.dll(AssemblyName 为 TransactedComment)。

运行示例:安装模块并加载

原文档给出的运行方式分三步:

  1. 将生成的程序集复制到模块目录:[user]/Documents/WindowsPowerShell/Modules/TransactedComment(注意目录名必须与模块名一致);
  2. 启动 Windows PowerShell;
  3. 执行 Import-Module TransactedComment,将程序集加载到当前 PowerShell 会话中。

加载成功后,Add-TransactedComment、Get-TransactedComment、Clear-TransactedComment 三个命令即可用。

使用示例:完整的事务操作序列

Readme.txt 的 "Using the Sample" 一节给出了官方推荐的操作序列,它直观展示了"未提交不可见、提交后可见"的事务语义:

# 1. 启动一个新事务
Start-Transaction

# 2. 在事务内追加一条评论(关键:-UseTransaction 开关)
Add-TransactedComment -UseTransaction "Hello World!"

# 3. 不指定 -UseTransaction,读到的是已提交的(旧)值
Get-TransactedComment

# 4. 指定 -UseTransaction,读到的是事务内的暂存值
Get-TransactedComment -UseTransaction

# 5. 提交事务
Complete-Transaction

# 6. 事务结束后再次读取,此时"Hello World!"已经生效
Get-TransactedComment

理解这个序列的关键在于:-UseTransaction 是 SupportsTransactions = true 自动带来的开关参数。带上它,cmdlet 就参与到当前活动事务中;不带上它,cmdlet 直接作用于已提交的正式状态。因此第 3 步读到的是事务开始前的旧内容,第 4 步才能读到事务内的新内容,直到第 5 步 Complete-Transaction 提交后,第 6 步才读到合并后的最终结果。若改用 Undo-Transaction 回滚,则事务内写入的"Hello World!"将被丢弃,评论内容保持原样——这正是"可随事务一起提交或回滚的评论日志"的由来。

深入源码一:SupportsTransactionsAttribute 与 UseTransaction 参数

三个 cmdlet 类的声明方式完全一致,以 AddTransactedCommentCommand.cs 为例:

[Cmdlet("Add", "TransactedComment", SupportsTransactions = true)]
public class AddTransactedCommentCommand : PSCmdlet

SupportsTransactions = true 是事务机制的门户:

  • 它让 PowerShell 自动为 cmdlet 附加 -UseTransaction 开关参数;
  • 当用户携带 -UseTransaction 调用 cmdlet 且当前存在活动事务时,cmdlet 才会被纳入事务;
  • 声明了该属性的 cmdlet 才能在内部通过 CurrentPSTransaction 访问 PowerShell 事务。

GetTransactedCommentCommand 与 ClearTransactedCommentCommand 的声明与之完全相同,可见三者的实现路径(GetTransactedCommentCommand.cs、ClearTransactedCommentCommand.cs)。

此外,Add-TransactedComment 的 Comment 参数还演示了流水线(pipeline)支持:

[Parameter(Mandatory = true,
           Position = 0,
           ValueFromPipeline = true,
           ValueFromPipelineByPropertyName = true)]
public string[] Comment { get; set; }

它同时开启 ValueFromPipeline 与 ValueFromPipelineByPropertyName,因此可以执行 dir | Add-TransactedComment 之类的管道用法,把整个目录列表写入评论日志(源码注释明确提到这一场景,见 AddTransactedCommentCommand.cs)。

深入源码二:CurrentPSTransaction 与 using 块

CurrentPSTransaction 是 PSCmdlet 提供给支持事务 cmdlet 的属性,它表示"当前事务"的 .NET 表示。AddTransactedCommentCommand.ProcessRecord() 中的核心写法(AddTransactedCommentCommand.cs)如下:

protected override void ProcessRecord()
{
    TransactedComment current = this.MyInvocation.MyCommand.Module.PrivateData as TransactedComment;
    if (current == null)
    {
        current = new TransactedComment();
        this.MyInvocation.MyCommand.Module.PrivateData = current;
    }

    if (this.TransactionAvailable())
    {
        using (this.CurrentPSTransaction)
        {
            foreach (string comment in this.Comment)
            {
                current.Append(comment);
                current.Append(Environment.NewLine);
            }
        }
    }
    else
    {
        foreach (string comment in this.Comment)
        {
            current.Append(comment);
            current.Append(Environment.NewLine);
        }
    }
}

这段代码包含两个值得注意的设计细节:

  1. TransactionAvailable() 前置判断:只有显式携带 -UseTransaction 时 CurrentPSTransaction 才非空,才能进入 using 块;先判断再使用,使得同一 cmdlet 既能运行在事务内,也能运行在普通(非事务)上下文中,保持行为一致;
  2. using (this.CurrentPSTransaction) 块的作用:CurrentPSTransaction 实现了 IDisposable,using 块会把 PowerShell 的活动事务暴露为 .NET 的 Transaction.Current。这样,事务资源管理器(如 TransactedComment)就能以标准 .NET 事务 API 感知并登记到当前事务中——源码注释明确写到:"Within this using statement, PowerShell exposes the active transaction as Transaction.Current, allowing standard .NET transactional resource managers to participate."

GetTransactedCommentCommand(GetTransactedCommentCommand.cs)与 ClearTransactedCommentCommand(ClearTransactedCommentCommand.cs)遵循完全相同的模式:TransactionAvailable() 判断后,或是在 using (this.CurrentPSTransaction) 内读写,或是直接读写正式值。

深入源码三:.NET 事务资源管理器(TransactedComment)的实现

TransactedComment 类(TransactedComment.cs)实现了 System.Transactions.IEnlistmentNotification 接口,是一个教科书式的轻量级事务资源管理器。

双值快照机制

类内部维护两个 StringBuilder(TransactedComment.cs):

  • commentValue:评论的正式(已提交)值;
  • temporaryValue:事务内的临时值;
  • enlistedTransaction:记录当前有权操作该对象的事务引用,用于校验"是否处于正确的事务上下文"。

当对象第一次在事务内被修改时,ValidateTransactionOrEnlist()(TransactedComment.cs)会执行"登记 + 保存快照":

if (this.enlistedTransaction == null)
{
    Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
    this.enlistedTransaction = Transaction.Current;
    this.temporaryValue = new StringBuilder(this.commentValue.ToString());
}

即通过 EnlistVolatile 将自身登记为事务的易失参与方,并基于正式值制作临时快照。此后 Append/Clear 在事务内都只改动 temporaryValue(见 Append 与 Clear),正式值保持不变。

上下文校验:防止跨事务操作

ValidateTransactionOrEnlist() 同时负责一致性校验,违反规则时抛出 InvalidOperationException(TransactedComment.cs):

  • 若对象已被某个事务登记,而当前 Transaction.Current 是另一个事务,报错 "Cannot modify string. It has been modified by another transaction.";
  • 若对象仍处于某事务的登记状态,却在不带 -UseTransaction 的非事务上下文被修改,同样报错。

这意味着:一个被事务"占用"的 TransactedComment 在事务结束(提交或回滚)之前,不能从其他事务或普通上下文修改,从而保证数据不会被双重写入。

IEnlistmentNotification 的四个回调

事务管理器通过实现 IEnlistmentNotification 获得事务系统的回调(TransactedComment.cs):

回调方法 本示例行为
Prepare(PreparingEnlistment) 调用 preparingEnlistment.Prepared() 表示"可以提交"(两阶段提交的第一阶段)
Commit(Enlistment) 用 temporaryValue 整体替换 commentValue,清空临时值并解除登记,最后调用 enlistment.Done()
Rollback(Enlistment) 直接丢弃 temporaryValue 并解除登记,调用 enlistment.Done()
InDoubt(Enlistment) 结果不明时调用 enlistment.Done(),不做额外处理

Commit 的实现即"固化临时值"(TransactedComment.cs):

void IEnlistmentNotification.Commit(Enlistment enlistment)
{
    this.commentValue = new StringBuilder(this.temporaryValue.ToString());
    this.temporaryValue = null;
    this.enlistedTransaction = null;
    enlistment.Done();
}

Rollback 的实现即"丢弃临时值"(TransactedComment.cs):

void IEnlistmentNotification.Rollback(Enlistment enlistment)
{
    this.temporaryValue = null;
    this.enlistedTransaction = null;
    enlistment.Done();
}

另外,Length 属性与 ToString() 方法都遵循同样的可见性规则:在登记的同一事务内返回 temporaryValue,否则返回 commentValue(TransactedComment.cs、TransactedComment.cs),这也正是 Get-TransactedComment -UseTransaction 与不带开关时读取结果不同的底层原因。

模块隔离存储:PrivateData

三个 cmdlet 都通过 this.MyInvocation.MyCommand.Module.PrivateData 读写 TransactedComment 实例(例如 AddTransactedCommentCommand.cs):

TransactedComment current = this.MyInvocation.MyCommand.Module.PrivateData as TransactedComment;
if (current == null)
{
    current = new TransactedComment();
    this.MyInvocation.MyCommand.Module.PrivateData = current;
}

Module.PrivateData 是 PowerShell 为模块提供的、与当前模块和运行空间绑定的私有数据区。源码注释明确指出其价值:它提供与模块及运行空间关联的隔离存储,防止用户的会话中其他方面干扰评论数据。首次使用时惰性创建实例并写回 PrivateData,后续 cmdlet 直接从同一位置取回,从而保证 Add、Get、Clear 三个命令操作的是同一个评论存储。

行为验证与事务语义小结

将上述源码细节与 Readme.txt 的操作序列对照,可以总结出本示例的完整事务语义闭环:

  1. Start-Transaction 开启事务;
  2. Add-TransactedComment -UseTransaction "Hello World!" 在 using (CurrentPSTransaction) 内调用 Append,触发 EnlistVolatile 登记并写临时快照;
  3. 不带 -UseTransaction 的 Get-TransactedComment 读取正式值(旧内容);
  4. 带 -UseTransaction 的 Get-TransactedComment 在事务上下文内读取临时值(新内容);
  5. Complete-Transaction 触发两阶段提交,Prepare 通过后 Commit 将临时值固化为正式值;
  6. 事务结束后 Get-TransactedComment 读到合并后的最终值。

若在第 5 步改用 Undo-Transaction,则 Rollback 会丢弃 temporaryValue,评论保持事务开始前的状态。这套"临时值 + 正式值 + 四回调"的结构,正是把任意 .NET 对象接入 PowerShell 事务的最小可行模板。

进一步阅读

登录后查看全文
Windows-classic-samples