Skip to main content
skill CX Codex

multithreaded-task-migration — Claude Code skill: setup guide

multithreaded-task-migration guides the migration of MSBuild tasks to multithreaded execution. Helps implement TaskEnvironment and audit thread-safety traps.

MIT ★ 5,556 updated 2026-10-29

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add dotnet/msbuild --skill multithreaded-task-migration -a claude-code
Open on GitHub

What multithreaded-task-migration does

The skill establishes rules for adapting MSBuild tasks to concurrent execution. Each concrete class must declare [MSBuildMultiThreadableTask] directly because the attribute is not inherited. Tasks interacting with disk, child processes, or environment variables implement IMultiThreadableTask to receive a TaskEnvironment.

Path resolution represents the biggest risk during migration. The MSBuildTask0003 analyzer checks only standard IO types like File or Directory. Methods like AssemblyName.GetAssemblyName or IO wrapped in helper interfaces bypass it entirely. A clean analyzer run does not guarantee thread safety unless every path is resolved early via TaskEnvironment.GetAbsolutePath().

Unit tests for built-in tasks configure the environment automatically. Custom or third-party tasks require setting TaskEnvironment.Fallback directly within test fixtures.

What it helps with

  • migrate MSBuild tasks to multithreaded execution
  • replace process-wide environment calls with TaskEnvironment
  • resolve relative paths using TaskEnvironment.GetAbsolutePath
  • detect file system calls that bypass the MSBuildTask0003 analyzer

Example prompts for the agent

  • Check this MSBuild task for multithreaded execution compliance
  • Refactor MyTask to use IMultiThreadableTask and isolate process state
  • Audit path resolution in this task to catch analyzer-invisible disk access

How to install multithreaded-task-migration

1Skills CLI (Vercel)

npx skills add dotnet/msbuild --skill multithreaded-task-migration -a claude-code

2Manually: put the files in place

~/.claude/skills/multithreaded-task-migration/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/multithreaded-task-migration/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about multithreaded-task-migration

How to install multithreaded-task-migration in Claude Code?

Run npx skills add dotnet/msbuild --skill multithreaded-task-migration -a claude-code.

What does multithreaded-task-migration do?

It provides migration patterns and red-team review checklists to convert MSBuild tasks to thread-safe execution without shared process state.

Why is a passing MSBuildTask0003 analyzer check insufficient?

The analyzer inspects only a fixed list of System.IO types. APIs like AssemblyName.GetAssemblyName or disk access behind interfaces produce no diagnostic warnings.

Source text

SKILL.md · MIT
---
name: multithreaded-task-migration
description: Guide for migrating MSBuild tasks to multithreaded mode support, including compatibility red-team review. Use this when converting tasks to thread-safe versions, implementing IMultiThreadableTask, adding TaskEnvironment support, or auditing migrations for behavioral compatibility.
---

# Migrating MSBuild Tasks to Multithreaded API

MSBuild's multithreaded execution model requires tasks to avoid global process state (working directory, environment variables). Thread-safe tasks declare this capability via `MSBuildMultiThreadableTask` and use `TaskEnvironment` from `IMultiThreadableTask` for safe alternatives.

## Migration Steps

### Step 1: Update Task Class Declaration

a. Ensure the task implementing class is decorated with the `MSBuildMultiThreadableTask` attribute.
b. Implement `IMultiThreadableTask` **only if** the task needs `TaskEnvironment` APIs (path absolutization, env vars, process start). If the task has no file/environment operations (e.g., a stub class), the attribute alone is sufficient.

```csharp
[MSBuildMultiThreadableTask]
public class MyTask : Task, IMultiThreadableTask
{
    public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;
    ...
}
```

**Note**: `[MSBuildMultiThreadableTask]` has `Inherited = false` — it must be on each concrete class, not just the base. The corollary is easy to miss: the base class still executes multithreaded, but is not analyzed. Audit the whole base chain — see [Unsafe Code in an Unannotated Base Class](#unsafe-code-in-an-unannotated-base-class).

### Step 2: Absolutize Paths Before File Operations

All path strings must be absolutized with `TaskEnvironment.GetAbsolutePath()` before use in file system APIs. This resolves paths relative to the project directory, not the process working directory.

```csharp
AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(inputPath);
if (File.Exists(absolutePath))
{
    string content = File.ReadAllText(absolutePath);
}
```

The [`AbsolutePath`](https://github.com/dotnet/msbuild/blob/main/src/Framework/PathHelpers/AbsolutePath.cs) struct:
- `Value` — the absolute path string
- `OriginalValue` — preserves the input path (use for error messages and `[Output]` properties)
- Implicitly convertible to `string` for File/Directory API compatibility
- `GetCanonicalForm()` — resolves `..` segments and normalizes separators (see [Sin 5](#sin-5-canonicalization-mismatch))

**CAUTION**: `GetAbsolutePath()` throws `ArgumentException` for null/empty inputs. See [Sin 3](#sin-3-null-coalescing-that-changes-control-flow) and [Sin 6](#sin-6-exception-type-change) for compatibility implications.

### Step 3: Replace Environment Variable APIs

| BEFORE (UNSAFE)                                  | AFTER (SAFE)                                       |
|--------------------------------------------------|----------------------------------------------------|
| `Environment.GetEnvironmentVariable("VAR");`       | `TaskEnvironment.GetEnvironmentVariable("VAR");`     |
| `Environment.SetEnvironmentVariable("VAR", "v");`  | `TaskEnvironment.SetEnvironmentVariable("VAR", "v");` |

### Step 4: Replace Process Start APIs

| BEFORE (UNSAFE - inherits process state)           | AFTER (SAFE - uses task's isolated environment)     |
|----------------------------------------------------|-----------------------------------------------------|
| `var psi = new ProcessStartInfo("tool.exe");`      | `var psi = TaskEnvironment.GetProcessStartInfo();`  |
|                                                    | `psi.FileName = GetFullPathToTool(); // must be absolute` |

## Updating Unit Tests

Built-in MSBuild tasks now initialize `TaskEnvironment` with a `MultiProcessTaskEnvironmentDriver`-backed default. Tests creating instances of built-in tasks no longer need manual `TaskEnvironment` setup. For custom or third-party tasks that implement `IMultiThreadableTask` without a default initializer, set `TaskEnvironment = TaskEnvironment.Fallback` (or use `TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(path)` to point at a specific project directory).

## APIs to Avoid

| Category | APIs | Alternative |
|---|---|---|
| **Forbidden** | `Environment.Exit`, `FailFast`, `Process.Kill`, `ThreadPool.SetMin/MaxThreads`, `Console.*` | Return false, throw, or use `Log` |
| **Use TaskEnvironment** | `Environment.CurrentDirectory`, `Get/SetEnvironmentVariable`, `Path.GetFullPath`, `ProcessStartInfo` | See Steps 2-4 |
| **Need absolute paths** | `File.*`, `Directory.*`, `FileInfo`, `DirectoryInfo`, `FileStream`, `StreamReader/Writer` | Absolutize first (File System APIs) |
| **Need absolute paths (analyzer-invisible)** | `AssemblyName.GetAssemblyName`, `XDocument/XElement/XmlDocument.Load(string)`, `XmlReader/XmlWriter.Create(string)`, `ZipFile.*`, `X509CertificateLoader`, `Image.FromFile`, `Assembly.LoadFrom` | Absolutize first — **the analyzer does not flag these** |
| **Review required** | `Assembly.Load*`, `Activator.CreateInstance*` | Check for version conflicts |

### Analyzer-Invisible Path Consumers

`MSBuildTask0003` monitors a fixed list of types (`File`, `Directory`, `FileInfo`, `DirectoryInfo`, `FileStream`, `StreamReader`, `StreamWriter`, `FileSystemWatcher`). Any *other* API that accepts a path string and touches disk is equally unsafe but produces **no diagnostic**.

In a ~150-task migration across dotnet/arcade, dotnet/source-build-assets and the dotnet/dotnet VMR, `AssemblyName.GetAssemblyName` on a raw input was the single most-repeated defect. Do not treat a clean analyzer run as evidence that path handling is complete — see [Verification](#verification-a-clean-analyzer-run-is-not-a-migration).

Note the overload distinction: the *string* overloads are hazards; `XDocument.Load(stream)` and `new StreamReader(stream)` are fine, because the caller already resolved the path to open the stream.

## Practical Notes

### CRITICAL: Trace All Path String Usage

Trace every path string through all method calls and assignments to find all places it flows into file system operations — including helper methods that may internally use File System APIs.

1. Find every path string (e.g., `item.ItemSpec`, function parameters)
2. Trace downstream through all method calls
3. Absolutize BEFORE any code path that touches the file system
4. Use `OriginalValue` for user-facing output (logs, errors) — see [Sin 2](#sin-2-errorlog-message-path-inflation)

**Trace through abstractions, not just concrete calls.** A path can reach the file system without a single `System.IO` type appearing in the task. In `InstallDotNetTool` (dotnet/arcade), the `DestinationPath`, `DotnetPath` and `WorkingDirectory` inputs flow raw through `IFileSystem` and `ICommandFactory` interfaces — the task body looks completely clean, and the analyzer reports nothing. When a task input is passed to an interface or delegate, resolve it at the task boundary rather than hoping the implementation does.

**Resolve once, at the boundary.** The recurring failure is not "forgot to absolutize" but "absolutized at three of four use sites". If a variable is going to be used as a path at all, convert it to `AbsolutePath` where it enters the task and keep it that way — see [Sin 8](#sin-8-swallowed-exceptions-hiding-an-unresolved-path).

### Exception Handling in Batch Operations

In batch processing (iterating over files), `GetAbsolutePath()` throwing on one bad path aborts the entire batch. Match the original task's error semantics:

```csharp
bool success = true;
foreach (ITaskItem item in SourceFiles)
{
    try
    {
        AbsolutePath path = TaskEnvironment.GetAbsolutePath(item.ItemSpec);
        ProcessFile(path);
    }
    catch (ArgumentException ex)
    {
        Log.LogError("Invalid path '{0}': {1}", item.ItemSpec, ex.Message);
        success = false;
    }
}
return success;
```

### Prefer AbsolutePath Over String

Stay in the `AbsolutePath` world — it's implicitly convertible to `string` where needed. Avoid round-tripping through `string` and back.

### TaskEnvironment is Not Thread-Safe

If your task spawns multiple threads internally, synchronize access to `TaskEnvironment`. Each task *instance* gets its own environment, so no synchronization between tasks is needed.

### API Discipline When Plumbing Through Helpers

When the migration ripples into shared helpers:

- **Helper signatures: take `AbsolutePath`, not `(string path, string pathForMessages)`**. Two-string signatures drift apart; the caller passing one `AbsolutePath` keeps `.Value` and `.OriginalValue` in lockstep.
- **Repo-wide helpers belong in an extensions class** (e.g., `TaskEnvironmentExtensions`), not on the task. If a per-task helper looks generic, extract it.
- **Don't condition behavior on MT-mode**. `TaskEnvironment.Fallback` already gives single-process semantics; `if (mtMode) { … } else { … }` doubles the maintenance surface and skips test coverage of one branch.
- **Don't silently swallow `ArgumentException` from `GetAbsolutePath`** in a helper — log a diagnostic so customers can debug bad inputs.

## References

- [Thread-Safe Tasks Spec](https://github.com/dotnet/msbuild/blob/main/documentation/specs/multithreading/thread-safe-tasks.md)
- [`AbsolutePath`](https://github.com/dotnet/msbuild/blob/main/src/Framework/PathHelpers/AbsolutePath.cs)
- [`TaskEnvironment`](https://github.com/dotnet/msbuild/blob/main/src/Framework/TaskEnvironment.cs)
- [`IMultiThreadableTask`](https://github.com/dotnet/msbuild/blob/main/src/Framework/IMultiThreadableTask.cs)

---

# Compatibility Red-Team Playbook

After migration, review for behavioral compatibility. **Every observable difference is a bug until proven otherwise.**

Observable behavior = `Execute()` return value, `[Output]` property values, error/warning message content, exception types, files written, and which code path runs.

## The 8 Deadly Compatibility Sins

Real bugs found during MSBuild task migrations. Every one shipped in initial "passing" code with green tests.

**Edge-case discipline:** For every migrated code path, verify behavior when inputs are `null`, empty string (`""`), or whitespace-only. `GetAbsolutePath` throws `ArgumentException` on null/empty — if the pre-migration code handled these differently (e.g., returned early, used a default, or threw a different exception type), the migration must preserve that behavior. Even if a scenario seems unlikely, treat it as a relevant finding if it is theoretically possible.

### Sin 1: Output Property Contamination

Absolutized values leak into `[Output]` properties that users/other tasks consume.

```csharp
// BROKEN: ManifestPath was "bin\Release\app.manifest", now "C:\repo\bin\Release\app.manifest"
AbsolutePath abs = TaskEnvironment.GetAbsolutePath(Path.Combine(OutputDirectory, name));
ManifestPath = abs; // implicit string conversion!

// CORRECT: separate original form from absolutized path
string originalPath = Path.Combine(OutputDirectory, name);
AbsolutePath outputPath = TaskEnvironment.GetAbsolutePath(originalPath);
ManifestPath = originalPath;          // [Output]: original form
document.Save((string)outputPath);    // file I/O: absolute path
```

**Detect**: For every `[Output]` property, trace backward — is it ever assigned from an `AbsolutePath`?

### Sin 2: Error/Log Message Path Inflation

Error messages and exception messages show absolutized paths instead of the user's original input.

**Direct leakage** — passing an `AbsolutePath` to logging APIs:

```csharp
// BROKEN: "Cannot find 'C:\repo\app.manifest'" instead of "Cannot find 'app.manifest'"
AbsolutePath abs = TaskEnvironment.GetAbsolutePath(path);
Log.LogError("Cannot find '{0}'", abs); // implicit conversion!

// CORRECT: use OriginalValue
Log.LogError("Cannot find '{0}'", abs.OriginalValue);
```

**Indirect leakage** — exception messages from helpers that received the absolutized path:

```csharp
// BROKEN: ex.FileName / ex.Message embed the absolutized path
catch (FileNotFoundException ex) { Log.LogError("Not found: {0}", ex.FileName); }
catch (Exception ex)              { Log.LogError(ex.Message); }

// CORRECT: prefer the original input; if you must use the exception, sanitize
catch (FileNotFoundException ex) { Log.LogError("Not found: {0}", abs.OriginalValue); }
catch (Exception ex)              { Log.LogError(ex.Message.Replace(abs.Value, abs.OriginalValue)); }
```

**Detect**: Search every `Log.LogError`/`LogWarning`/`LogMessage` — is any argument an `AbsolutePath`? Also check every `Log.LogError(ex.Message …)` / `ex.FileName` downstream of a `GetAbsolutePath` — did the exception originate from a helper that received the absolutized path?

### Sin 3: Null Coalescing That Changes Control Flow

Adding `?? ""` silently swallows an exception the old code relied on for error handling.

```csharp
// BEFORE: Path.GetDirectoryName("C:\") → null → Path.Combine(null, x) → ArgumentNullException
//   → task fails with an exception / error logged → Execute() returns false

// BROKEN: ?? "" added "for safety"
string dir = Path.GetDirectoryName(fileName) ?? string.Empty;
// Path.Combine("", x) succeeds silently → no error → Execute() returns TRUE!
```

**Detect**: For every `??` you added, ask: "What happened when this was null before?" If it threw and was caught → your `??` is a bug.

### Sin 4: Try-Catch Scope Mismatch

`GetAbsolutePath()` inside a try block leaves the absolutized value out of scope in the catch block. Helper methods in the catch (like `LockCheck`) then use the original non-absolute path.

```csharp
// CORRECT: hoist above try so catch can use it too
AbsolutePath abs = TaskEnvironment.GetAbsolutePath(OutputManifest.ItemSpec);
try {
    WriteFile(abs);
} catch (Exception ex) {
    string lockMsg = LockCheck.GetLockedFileMessage(abs);        // absolute → correct file
    Log.LogError("Failed: {0}", OutputManifest.ItemSpec, ...);   // original → user-friendly
}
```

**Detect**: For every `GetAbsolutePath` inside a try, check if the catch block needs the absolutized value.

### Sin 5: Canonicalization Mismatch

`GetAbsolutePath` does NOT canonicalize. `Path.GetFullPath` does TWO things: absolutize AND canonicalize (`..` resolution, separator normalization). If the old code used `Path.GetFullPath` for dictionary keys, comparisons, or display, you must add `.GetCanonicalForm()`:

```csharp
// GetAbsolutePath("foo/../bar")  → "C:\repo\foo/../bar"  (NOT canonical)
// Path.GetFullPath("foo/../bar") → "C:\repo\bar"         (canonical)

// BROKEN for dictionary keys — "C:\repo\foo\..\bar" ≠ "C:\repo\bar"
var map = items.ToDictionary(p => (string)TaskEnvironment.GetAbsolutePath(p.ItemSpec), ...);

// CORRECT
var map = items.ToDictionary(
    p => (string)TaskEnvironment.GetAbsolutePath(p.ItemSpec).GetCanonicalForm(),
    StringComparer.OrdinalIgnoreCase);
```

**Detect**: Find every `Dictionary`/`HashSet`/`ToDictionary` using path keys, and every place the old code called `Path.GetFullPath`. If canonicalization mattered, add `.GetCanonicalForm()`.

### Sin 6: Exception Type Change

Old code threw `FileNotFoundException` for missing files; new code throws `ArgumentException` from `GetAbsolutePath("")` before reaching the file check. Custom catch blocks filtering by exception type may be bypassed. (`ExceptionHandling.IsIoRelatedException` catches `ArgumentException`, but task-specific handlers might not.)

**Detect**: For every `GetAbsolutePath`, check what the old code threw for null/empty and whether the calling code has type-specific catch blocks.

### Sin 7: `Path.IsPathRooted` as an Absolutize Gate

`Path.IsPathRooted` returns `true` for **drive-relative** (`C:foo\bar`) and **root-relative** (`\foo\bar`) Windows paths — both still depend on process current-directory / current-drive state. "Absolutize only if not rooted" silently leaves those paths process-dependent.

`GetAbsolutePath` correctly handles all path forms — including the Windows edge cases (`C:foo`, `\foo`) that `Path.IsPathRooted` considers "rooted" but that are still CWD/drive-dependent. Call it unconditionally; remove any `IsPathRooted` short-circuit.

### Sin 8: Swallowed Exceptions Hiding an Unresolved Path

The usual mental model is "unresolved path → `FileNotFoundException` → loud failure". That model is wrong wherever a `catch` treats an exception as a *semantic answer*. There, an unresolved path does not fail the build — it silently returns the wrong answer.

Real example from the dotnet/dotnet VMR (`CheckForPoison`), where the same variable is resolved three lines later:

```csharp
// BROKEN
try
{
    AssemblyName asm = AssemblyName.GetAssemblyName(fileToCheck);   // raw, relative-capable
    ...
    if (IsAssemblyFromSbrp(TaskEnvironment.GetAbsolutePath(fileToCheck))) { ... }   // resolved
    else if (IsAssemblyPoisoned(TaskEnvironment.GetAbsolutePath(fileToCheck))) { ... }
}
catch (BadImageFormatException) { /* not a managed assembly - fine */ }
```

The `GetAssemblyName` call is only an "is this a managed assembly?" probe, and the catch means "not an assembly". So an unresolved path throws, gets swallowed, and **both poison checks are skipped** — turning a leaked binary into a false negative in the leak-detection gate itself. The build stays green while the check it exists to perform quietly stops working.

This sin is especially dangerous because it defeats the usual verification strategy: the decoy-CWD test (Pattern A) still "passes" unless it asserts on the *result*, not just on `Execute()` returning true.

**Detect**: For every `catch` in a migrated task, ask what the handler *means*. If it means anything other than "fail" — "not an assembly", "not found, use default", "unsupported, skip" — then every path-consuming call inside the corresponding `try` must be absolutized, and the catch should be narrowed to the exception types that genuinely represent that semantic answer (`BadImageFormatException` here, **not** `IOException`/`ArgumentException`).

---

## Call-Chain Hazards Beyond the Task

The 7 sins above are *local* to the task body. The other half of MT migration is auditing the **transitive call chain** — helpers and shared utility classes the task reaches into.

### Helpers That Capture Process State

Helpers reached from `Execute()` can quietly depend on process state in any of these ways:

- A relative path falls through to `Directory.GetCurrentDirectory()` (often as a "fallback") or to `Path.GetFullPath(x)` without a base.
- An env var is read directly via `Environment.GetEnvironmentVariable` (not `TaskEnvironment`).
- A `static` field is seeded from process state on first use (`static string s_x = Directory.GetCurrentDirectory()`), permanently capturing the first caller's environment for every later caller.
- A BCL API echoes its input path back through `ex.Message` / `ex.FileName` (Sin 2).
- The helper takes a `string path` and returns a `string` — losing the `.OriginalValue` distinction, so callers either lie in messages or absolutize twice.

**Resolution patterns:**

1. Add an MT-aware overload that takes `TaskEnvironment` (or an `AbsolutePath` / explicit fallback path). Legacy overload delegates with `TaskEnvironment.Fallback`. Don't branch on "MT mode on/off".
2. Promote the parameter type to `AbsolutePath` so `.Value` and `.OriginalValue` travel together.
3. Replace process-state-seeded static caches with `ConcurrentDictionary<TKey, TValue>` keyed on the inputs that determine uniqueness — never on process state.
4. For cross-repo helpers (foundation types used by many tasks), migrate the foundation in a dedicated PR before the tasks that consume it; the hydration step is usually where `Path.GetFullPath` is hiding.

### Unsafe Code in an Unannotated Base Class

`[MSBuildMultiThreadableTask]` is `Inherited = false`, so it goes on each concrete task. The consequence people miss is the mirror image: **the base class runs multithreaded too, but nothing marks it as such** — and with `msbuild_task_analyzer.scope = multithreadable_only` (the recommended setting for incremental migration) the analyzer does not look inside it at all.

From dotnet/arcade: `CreateAkaMSLinks` and `DeleteAkaMSLinks` were both annotated, both analyzer-clean. Their shared base contained:

```csharp
// AkaMSLinksBase - NOT annotated, so never analyzed
File.ReadAllText(ClientCertificate)   // ClientCertificate is a task input property
```

A monitored API (`File`) on a raw task input — exactly what the analyzer exists to catch — invisible purely because of where it lived.

**Resolution:** when you annotate a task, audit its full base chain up to `Task`/`ToolTask`. If the base holds shared input properties or path handling, have the **base** implement `IMultiThreadableTask` and do the resolution there, so every derived task inherits the fix:

```csharp
public abstract class AkaMSLinksBase : Task, IMultiThreadableTask
{
    public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;
    // ... resolve ClientCertificate here, once, for all derived tasks
}
```

Note that implementing `IMultiThreadableTask` on the base is safe and does not change routing — routing keys off the attribute, which stays on the concrete classes.

### Engine-Owned Shared State: `RegisterTaskObject`

The guidance about `static` fields has a less obvious sibling: `IBuildEngine4.GetRegisteredTaskObject` / `RegisterTaskObject`. Under MT, in-process thread nodes share this engine-owned state. Tasks in different worker or TaskHost processes do not.

Using these APIs is a **review signal, not a warning**. Check object thread safety, key collisions, and whether correctness depends on two task invocations sharing a cache.

The get/register sequence is not atomic. Two tasks can both miss and create an object. Only one equal-key object is retained; `RegisterTaskObject` returns no result, and MSBuild does not dispose an unretained object. Whether that matters depends on what is cached:

| Cached computation | Review result |
|---|---|
| Pure and deterministic for the key | Safe if the losing object needs no cleanup, or the task cleans it up |
| Deduplication is the point, such as logging once per build | Unsafe because both tasks can perform the side effect |
| A failure | Check that the key includes every input that affects the result; otherwise do not cache it |

Real examples from dotnet/arcade: `LocateDotNet` was safe because its computation was pure. `SingleError` was not safe because its purpose was to emit exactly one error per build, so its annotation was removed.

### Tasks Instantiated Directly by Other Tasks

`[MSBuildMultiThreadableTask]` is only honored when the TaskFactory creates the task (i.e., a target invokes it as `<MyTask … />`). A task created via `new MyTask()` inside another task's body bypasses the factory and **never gets `TaskEnvironment` injected** — it silently defaults to `TaskEnvironment.Fallback` (= process CWD).

Migrating a nested task in isolation is therefore meaningless. Either migrate the parent and have it explicitly propagate its `TaskEnvironment` to the nested instance before calling `Execute()`, or restructure so the nested task is a regular TaskFactory-created task.

**Detect:** grep for `new …Task()` followed by `.Execute()` — every direct instantiation is a hole.

### ToolTask Override Hot Spots

`ToolTask` subclasses inherit virtual methods that run *before or after* `Execute()` and frequently touch the file system. Audit every override:

| Override | Hazard | Migration |
|---|---|---|
| `GenerateFullPathToTool()` | Builds `ProcessStartInfo.FileName` — relative tool path → wrong tool launched | Absolutize the tool path before returning |
| `SkipTaskExecution()` | Up-to-date check on input/output timestamps using relative paths | Absolutize both sides of the comparison |
| `ValidateParameters()` | `File.Exists` on input parameters | Absolutize before probing |
| `GenerateResponseFileCommands()` / `GenerateCommandLineCommands()` | Tempting to absolutize args | **Don't** — the child's `WorkingDirectory` is the project dir, so relative args resolve correctly; absolutizing inflates user-visible output and can leak into tool diagnostics or generated artifacts |
| `GetWorkingDirectory()` | Default `null` → child inherits host CWD | Leave alone if you use `TaskEnvironment.GetProcessStartInfo()`; it already sets `WorkingDirectory` |

**Key contract:** `ProcessStartInfo.FileName` is resolved by the OS **before** `WorkingDirectory` takes effect, so the executable path must be absolute. Tool arguments are interpreted by the child process in its working directory, so they should stay relative.

### Engine-Owned Environment Variables Are Immutable in MT Mode

Env vars consumed by the engine *before* tasks run (e.g., `MSBUILD*`-prefixed flags and the framework/SDK discovery variables) are snapshotted into engine caches at startup. Tasks that mutate them later have no observable effect on the engine — but the mutation appears to succeed locally, masking bugs.

If a migrated task previously mutated such a variable to influence a downstream tool, re-architect to pass the value via `ProcessStartInfo.EnvironmentVariables` on the child process instead of mutating the parent's environment.

---

## Test Patterns for MT Migrations

A migration test must **fail when the migration is undone**. Tests that pass identically against pre- and post-migration code are theater. The two patterns below are the ones that reliably exercise MT-specific behavior.

### Pattern A: Decoy-CWD Test (for tasks that touch the file system)

Set the process working directory to a **decoy** dir with no relevant files; set `TaskEnvironment.ProjectDirectory` to a different dir with the inputs/expected outputs. The task must read/write against the project directory, not the decoy.

```csharp
using TestEnvironment env = TestEnvironment.Create();
TransientTestFolder projectDir = env.CreateFolder();
TransientTestFolder decoyCwd = env.CreateFolder();
File.WriteAllText(Path.Combine(projectDir.Path, "input.txt"), "expected");

env.SetCurrentDirectory(decoyCwd.Path); // auto-restored when env is disposed

var task = new MyTask
{
    TaskEnvironment = TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(projectDir.Path),
    Input = "input.txt", // relative
};
task.Execute().ShouldBeTrue();
```

**CRITICAL:** `Directory.SetCurrentDirectory` is **process-global**. xUnit parallelizes tests within a class by default — a CWD-mutating test will flake unless pinned to a non-parallel collection (`[Collection]` + `[CollectionDefinition(DisableParallelization = true)]`). The `IDisposable` restore protects sequential safety but not concurrent siblings.

### Pattern B: Cross-Instance Independence (for tasks doing relative-path resolution)

Two task instances, two `TaskEnvironment.ProjectDirectory` values, same relative input. Assert each task's output is rooted to its own project directory — proving resolution is per-instance, not shared.

### When NOT to Write a "Migration Test"

Attribute-only migrations (just `[MSBuildMultiThreadableTask]`, no `IMultiThreadableTask`) on tasks whose `Execute()` body contains no file/env/process/static-state interactions have nothing to test — a decoy-CWD test would pass whether the attribute is present or not. **Don't write the test.** Document the call-chain audit conclusion in the PR description instead.

### Test Hygiene

- Use `TestEnvironment` / `TransientTestFolder` for temp dirs; never `Path.GetTempPath() + Guid.NewGuid()` with manual `try/finally`.
- Hard-code expected assertion values; don't recompute them from `Path.Combine(...)` in the assertion — when the test fails you want to know what was actually wrong.

---

## Verification: A Clean Analyzer Run Is Not a Migration

`Microsoft.Build.TaskAuthoring.Analyzer` is the right first line of defense, and it should be enabled. It is not sufficient on its own, and it is worth being concrete about why so you know what work it leaves you.

**The data.** In a migration of ~150 tasks across dotnet/arcade, dotnet/source-build-assets and the dotnet/dotnet VMR, the analyzer was enabled in all three repos and every build was **0 warnings, 0 errors**. A manual audit afterwards found **9 real defects**:

| Why the analyzer missed it | Count | Example |
|---|---|---|
| The code was outside the analysis scope | 2 | unsafe call in an unannotated base class |
| The API is not on the monitored list | 3 | `AssemblyName.GetAssemblyName` |
| The failure class is not modeled at all | 4 | task-object race, memoized failure, nested task construction, path crossing a DI boundary |

The last row is the important one: those are dataflow and lifetime problems, not banned-API problems. No amount of allowlist tuning reaches them, which is why the [Red-Team Audit Protocol](#red-team-audit-protocol) below is not optional.

**Why "it worked when I tested it" is weak evidence.** An unresolved relative path in MT mode does not reliably throw. It resolves against whatever the shared node's current directory happens to be, which depends on which project scheduled first. So the same defect passes locally single-threaded every time, passes in CI most of the time, and fails occasionally on one machine under load. And per [Sin 8](#sin-8-swallowed-exceptions-hiding-an-unresolved-path), some never throw at all.

**Verification checklist.** The [Sign-Off Checklist](#sign-off-checklist) at the end of this document is the actionable list. The items most likely to be skipped — because nothing warns you about them — are:

1. The full base chain, not just the concrete class.
2. Every `catch`, classified: does it mean "fail", or a semantic answer? (Sin 8)
3. Every task input traced to *every* use site — the common defect is resolved at 3 of 4 sites, not 0 of 4.
4. Caches and memoization: `static` fields, `RegisterTaskObject`, and anything storing a failure.
5. A Pattern A or Pattern B test that fails when the migration is...

© dotnet · MIT · dotnet/msbuild

Similar skills

All skills for Backend and APIs →

Project sponsors

Companies that keep this analytics open