Logit.io
Why StartActivity returns null in a .NET worker
← Back to blog
11/24/2026 · 15 min read

Why StartActivity returns null in a .NET worker

Logit.io Team
Logit.io Team
Technical Content Team

Last updated 11/24/2026

How To GuidesResources

If ActivitySource.StartActivity returns null in a .NET worker, check whether a listener is attached to that source at the call site. Register the worker's actual ActivitySource name with AddSource and keep the TracerProvider alive until the operation finishes and the Activity stops. If a listener is attached, check the parent context and the sampler. An unsampled remote parent can produce a non-recording Activity that carries the trace context and yields zero exported spans. Prove which case you have in memory before troubleshooting transport or searching the backend.

The listings and commands below are illustrative. This guide runs the same billing operation four times in separate .NET 8 processes. You'll compare a working source registration with a mismatch, an early provider disposal and a remote unsampled parent. Each run prints listener presence, the return value, both sampling flags and the number of finished spans. Use the first difference to decide what to fix and what evidence to send to the APM team.

Contents

Establish the matched case

Suppose the worker reconciles a batch successfully and HTTP spans are visible, but the custom operation billing.reconcile is missing. Pick that one call site and reproduce it without the host, queue client or automatic instrumentation. Here the source is always Billing.Worker. The working matched case registers it, then the mismatch run treats the same source as the missing worker source by subscribing to Billing.Api. Keeping the actual source and operation fixed makes the comparison about the registration.

Four call-site observations

  1. Read HasListeners() on the actual source instance immediately before starting the operation. This is a snapshot of whether any listener is attached. A reading earlier in startup can miss a registration or disposal that happens before the worker runs.

  2. Capture the return value from StartActivity itself. A null return means this call created no Activity. Checking Activity.Current afterwards can show an existing parent and give a different answer.

  3. Read Recorded and IsAllDataRequested on the returned Activity while it is in scope. Use n/a for both when the result is null. A real Activity with both flags false is a different observation.

  4. Count finished spans after disposing the Activity. For a count of one, check that the span has the expected source and operation name. A count from the whole process on its own can include work unrelated to the missing span.

With no attached listeners, .NET returns null. With listeners attached, .NET evaluates their sampling requests for the operation. If every request leaves the result at None, the return is also null. That is why the listener check and the return value belong on separate lines. See the Microsoft StartActivity API reference and the .NET instrumentation walkthrough.

Local worker build

Save the two files below together in a directory with the .NET 8 SDK available. The project targets net8.0 and pins the OpenTelemetry SDK and InMemory exporter to 1.12.0. Use a plain terminal session without a profiler, startup hooks or automatic instrumentation that attaches trace listeners. Each invocation builds one provider and runs one example operation. The operation only yields once to exercise the asynchronous lifetime. The executable sends no data over the network. Restoring the packages is a separate step and can use a local package cache or offline feed.

Billing.Worker.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="OpenTelemetry" Version="[1.12.0]" />
    <PackageReference Include="OpenTelemetry.Exporter.InMemory" Version="[1.12.0]" />
  </ItemGroup>
</Project>

Program.cs

using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

const string sourceName = "Billing.Worker";
const string operationName = "billing.reconcile";

if (args.Length != 1 ||
    args[0] is not ("matched" or "mismatch" or "disposed" or "remote-unsampled"))
{
    Console.Error.WriteLine("Choose matched, mismatch, disposed, or remote-unsampled.");
    return 2;
}

string testCase = args[0];
string registeredName = testCase == "mismatch" ? "Billing.Api" : sourceName;
bool disposeBeforeStart = testCase == "disposed";
bool hasRemoteParent = testCase == "remote-unsampled";
ActivityContext parent = hasRemoteParent
    ? new ActivityContext(
        ActivityTraceId.CreateFromString("0123456789abcdef0123456789abcdef"),
        ActivitySpanId.CreateFromString("0123456789abcdef"),
        ActivityTraceFlags.None,
        isRemote: true)
    : default;

if (Activity.Current is not null)
{
    Console.Error.WriteLine("Run in a clean process without an ambient Activity.");
    return 1;
}

var exported = new List<Activity>();
using var source = new ActivitySource(sourceName);
using var provider = Sdk.CreateTracerProviderBuilder()
    .ConfigureResource(resource => resource.AddService("billing-worker"))
    .AddSource(registeredName)
    .SetSampler(new ParentBasedSampler(new AlwaysOnSampler()))
    .AddInMemoryExporter(exported)
    .Build();

if (disposeBeforeStart)
{
    provider.Dispose();
}

bool hasListeners = source.HasListeners();
bool started;
bool? recorded;
bool? allDataRequested;

using (Activity? activity = source.StartActivity(operationName, ActivityKind.Internal, parent))
{
    started = activity is not null;
    recorded = activity?.Recorded;
    allDataRequested = activity?.IsAllDataRequested;

    if (hasRemoteParent &&
        (activity?.TraceId != parent.TraceId || activity?.ParentSpanId != parent.SpanId))
    {
        Console.Error.WriteLine("The child did not preserve the remote context.");
        return 1;
    }

    await Task.Yield(); // Stand-in for the worker's awaited operation.
}

Console.WriteLine($"Case={testCase}");
Console.WriteLine($"Source={source.Name}");
Console.WriteLine($"AddSource={registeredName}");
Console.WriteLine($"ProviderAtStart={(disposeBeforeStart ? "disposed" : "active")}");
Console.WriteLine($"ParentSampled={(hasRemoteParent ? "false (remote)" : "n/a (root)")}");
Console.WriteLine($"HasListeners()={hasListeners}");
Console.WriteLine($"StartActivity={(started ? "non-null" : "null")}");
Console.WriteLine($"Recorded={FormatFlag(recorded)}");
Console.WriteLine($"IsAllDataRequested={FormatFlag(allDataRequested)}");
Console.WriteLine($"FinishedSpanCount={exported.Count}");

(bool Listeners, bool Started, bool? Recorded, bool? AllData, int Count) expected =
    testCase switch
    {
        "matched" => (true, true, true, true, 1),
        "remote-unsampled" => (true, true, false, false, 0),
        _ => (false, false, null, null, 0),
    };

if ((hasListeners, started, recorded, allDataRequested, exported.Count) != expected ||
    (testCase == "matched" &&
     (exported[0].Source.Name != sourceName || exported[0].DisplayName != operationName)))
{
    Console.Error.WriteLine("Unexpected result. Check for other listeners or instrumentation.");
    return 1;
}

return 0;

static string FormatFlag(bool? flag) => flag?.ToString() ?? "n/a";

From that directory, restore and build the project, then launch a fresh process for each row. Each of the last three invocations varies one input relative to the first. The program exits with status 1 if the observations differ from those in the table, including the identity of the exported matched-case span. In the remote case it also checks that the child kept the example parent's trace ID and used its span ID as the parent span ID.

dotnet restore Billing.Worker.csproj
dotnet build Billing.Worker.csproj --no-restore
dotnet bin/Debug/net8.0/Billing.Worker.dll matched
dotnet bin/Debug/net8.0/Billing.Worker.dll mismatch
dotnet bin/Debug/net8.0/Billing.Worker.dll disposed
dotnet bin/Debug/net8.0/Billing.Worker.dll remote-unsampled

Expected results

These are expected functional results for the example worker and pinned packages. The first three rows are root operations, so there is no parent sampled flag to inspect. The last row supplies a valid W3C context with its sampled bit clear. Provider state refers to the time of the call. The final column counts the spans in memory after the Activity's scope ends.

RunSource nameRegistered nameProvider stateParent sampled flagHasListeners()StartActivity returnRecordedIsAllDataRequestedExported count
matchedBilling.WorkerBilling.WorkerActiven/a (root)trueNon-null, recordedtruetrue1
mismatchBilling.WorkerBilling.ApiActiven/a (root)falsenulln/an/a0
disposedBilling.WorkerBilling.WorkerDisposedn/a (root)falsenulln/an/a0
remote-unsampledBilling.WorkerBilling.WorkerActivefalse (remote)trueNon-null, propagation onlyfalsefalse0

Use the matched row as the gate for comparing the others. It exercises the same source, call and exporter as the other runs and confirms that stopping that operation produces one finished span. A failed matched case sends you back to the local process. With a working matched case, the two null rows show why a zero count alone cannot tell you whether registration or lifetime failed. The remote row is another zero, with trace context still available to the operation.

Match the ActivitySource to the provider

Source name and AddSource

Start by reading source.Name on the object that calls StartActivity. Then look at the AddSource registration on the provider the worker actually uses. The sample calls AddSource with Billing.Api in the mismatch case. That subscription names a different source, so the isolated Billing.Worker has no listener. The 1.12.0 SDK compares literal source names case-insensitively. Sharing the actual name constant where practical prevents differences in the text, such as a renamed component or an extra suffix. See the 1.12.0 provider source.

The three names in the sample serve different purposes. billing-worker is the service.name resource attribute and identifies the service that produces the telemetry. Billing.Worker is the ActivitySource name and identifies the instrumentation scope that produced the span. The provider uses that scope name when deciding whether to attach. billing.reconcile is the operation name you should see on the span. An API and a worker can use different service names and share an instrumentation library whose source name is the same in each process. If the worker runs only in one deployment mode, trace the registration through that mode's startup branch. A matching AddSource in a different executable or in a branch the worker skipped does nothing for the provider in this process.

When the process has additional instrumentation, HasListeners() can be true because a different listener attached. .NET considers the sampling requests of the attached listeners, and a request for more data can change the returned Activity and its flags. An HTTP span confirms that the HTTP source got a span through its configured path. Use the worker source instance and its own registration to check the billing operation. See the OpenTelemetry .NET tracing best practices.

Test lifetime and parent sampling

Provider lifetime

Check three points in the worker's timeline. The provider should be built before the call. It should still be alive when the awaited work finishes and the Activity is disposed. Shutdown should then give the configured processor time to handle finished spans. The disposed run isolates the first lifetime failure by calling Dispose() before HasListeners() and StartActivity. The SDK detaches its listener on disposal, so a previously working source can return null when the next job starts.

In a short-lived console worker, a provider scoped to a startup helper can end before the consumer loop begins. A task that escapes a provider's using block creates a race. It may start after disposal and return null, or it may start earlier and lose the provider before the span ends. In a hosted BackgroundService, make sure the operations the host waits for include the work you want traced. If a job runs during shutdown, check that its completion is awaited and its Activity stops before tracing is torn down.

The example below uses a short-lived console worker whose setup starts a task inside the provider scope and awaits it outside. The updated code registers the source it actually uses and awaits the operation inside the lifetime of the same provider. Keep your existing sampler and exporter configuration on that builder where applicable. The demo's Task.Yield() stands in for the awaited job.

--- a/Program.cs
+++ b/Program.cs
@@ -1,25 +1,21 @@
 using System.Diagnostics;
 using OpenTelemetry;
 using OpenTelemetry.Trace;
 
 using var source = new ActivitySource("Billing.Worker");
 var exported = new List<Activity>();
 
-Task work;
-using (var provider = Sdk.CreateTracerProviderBuilder()
-    .AddSource("Billing.Api")
+using var provider = Sdk.CreateTracerProviderBuilder()
+    .AddSource("Billing.Worker")
     .AddInMemoryExporter(exported)
-    .Build())
-{
-    work = Task.Run(ProcessOneAsync);
-}
+    .Build();
 
-await work;
+await ProcessOneAsync();
 
 Console.WriteLine(exported.Count);
 
 async Task ProcessOneAsync()
 {
     using var activity = source.StartActivity("billing.reconcile");
     await Task.Yield();
 }

The Activity stays inside the operation method, so exiting the method stops it before the top-level provider is disposed. That ordering also works when the awaited operation throws because the using declarations unwind their scopes. For a worker with multiple jobs, keep the provider at the process or host level and scope each Activity to its own operation. Apply the same ordering when draining work on cancellation.

Null, propagation-only and recorded activities

This example explicitly uses ParentBasedSampler with an AlwaysOnSampler for roots. The matched case has no ambient Activity, so its empty parent context yields a root with both flags true. The remote run passes a context with a valid trace ID and span ID, isRemote: true and ActivityTraceFlags.None. The parent-based sampler chooses its unsampled remote branch and drops recording for that child. See OpenTelemetry .NET sampling and the 1.12.0 parent-based sampler source.

In SDK 1.12.0, the listener maps that drop decision to PropagationData for a remote parent. .NET uses that result to create a minimal Activity and carry forward the trace context. Under this setup, Recorded and IsAllDataRequested are both false and the SDK skips forwarding the stopped Activity to the processor. For a dropped child of a local parent, the SDK can return None. When this is the only listener, that yields null. The relevant sources are the pinned SDK listener implementation and the .NET 8 ActivitySource implementation.

This example runs on .NET 8 and obtains its Activity API through the SDK's transitive DiagnosticSource dependency. The 1.12.0 API package declares DiagnosticSource 9.0.0 as its minimum. That implementation also evaluates the attached listeners and creates an Activity when the combined request is above None. See the 1.12.0 package dependencies and the DiagnosticSource 9.0.0 implementation.

Recorded exposes the sampled flag. IsAllDataRequested tells instrumentation whether a listener requested the data needed for details such as tags and events. These signals can differ, for example when an SDK sampler returns RecordOnly and the runtime creates an Activity requesting data without setting the sampled flag on a root. A null return has neither signal. Capture both at the call site and check the exporter count independently after the stop.

For a real queue worker, capture whether the operation used an explicit extracted parent or inherited Activity.Current. Passing a default context can still use an ambient Activity. A direct call in a console process can therefore be a sampled root while the same handler in production is part of an unsampled trace. If the root matched case works, repeat your local check with an example parent that has the same sampled and remote flags as the failing operation. Compare the result with the sampler you actually configured.

Follow the completed Activity to export

Stopped Activity and export

At a breakpoint inside the using block, the matched case has started and the in-memory list can still be empty. Step past the block to let disposal stop the Activity. In 1.12.0, AddInMemoryExporter uses a simple export processor for traces. The finished matched-case span reaches the list during the stop, so the example reads the list before leaving the provider scope and needs no explicit flush. See the 1.12.0 InMemory exporter registration.

If the recorded Activity exists but the count is still zero in your adapted check, first confirm that execution leaves the scope you are measuring. A worker can finish an inner task while the Activity wraps an outer loop that is still running. Put the span around one job and inspect the list after that job exits. If you are collecting several jobs in one process, compare the exported operation and trace or span ID alongside the count so a span from an earlier job cannot satisfy the check.

In a short-lived application that uses a batch processor, check whether the Activity stops while the provider is active and whether the process gives that processor time to drain at shutdown. If you use ForceFlush as a diagnostic, call it after the stop while the provider is alive and inspect its result. A flush works on data that has reached the pipeline already. If the worker returns before its operation finishes, fixing the awaited work and Activity scope comes first.

Once the worker produces its finished local span, use the Logit.io .NET setup guide for the supported export path. If your application configures export through JSON, use the Logit.io appsettings walkthrough to check those settings against your existing registration.

For the backend handoff, start with the resource service name and a time window covering the worker run. In this example the service would be billing-worker and the span to inspect would be billing.reconcile. Send the APM owner the actual service name, operation name, UTC run window and the four local observations. With those details they can search by service and time and inspect the relevant trace in Jaeger. See viewing spans and traces in Jaeger.

FAQ

Can HTTP spans be visible while my worker span is missing?

Yes. The HTTP instrumentation can have a listener and produce finished spans while your worker source has no matching subscription. A single worker operation can also have a different parent sampling result. Check the actual worker source and the return from the call you want to trace.

Why is HasListeners true when StartActivity returns null?

A listener can subscribe to the source and still decline to create an Activity for a particular operation. Check the parent and sampler at that call. If the listener can attach or detach while work is running, also check the timing between the listener snapshot and the start call.

Does an unsampled parent always produce a null child?

The remote unsampled parent in this example produces a non-null Activity with both flags false and an export count of zero. A local unsampled parent can yield a different creation result under the same SDK. The configured sampler and any other attached listeners can also change the result.

What does the free trial include?

The 14-day Logit.io free trial includes every feature, including Hosted OpenTelemetry and APM trace viewing in Jaeger. No credit card is required. See getting started with Logit.io.

Next steps

Run the matched case, then reproduce the first failing check with the real worker's source, provider lifetime or parent flags. Put the registration and lifetime diff in the worker's code review along with the local result. When you can identify the completed span in memory, follow the Logit.io .NET Hosted OpenTelemetry guide to configure the supported export path.

Start Free Trial

Unlock complete visibility with hosted ELK, Grafana, and Prometheus-backed Observability

Start Free Trial

Get the latest Elastic Stack & logging resources when you subscribe

Want to see this in action?
Start a free trial and connect logs to your alert workflows.