© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
11 replies
UltraWelfare

Primary constructor parameter is null after being run in a Task

The following snippet of code is responsible for starting a background service

public class PeriodicCallingIdentificationService(CallService callService)
{
    private Task? _executeTask;
    private CancellationTokenSource? _stoppingCts;
    private Modem? _modem;

    public void StartExecuting(CancellationToken cancellationToken)
    {
        if (_modem is null) throw new InvalidOperationException("Can't start executing without modem");
        _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        _executeTask = Task.Run(async () =>
        {
            await DoWork(_stoppingCts.Token); // <-- here
            _modem.Close();
            _modem = null;
        }, cancellationToken);
    }
public class PeriodicCallingIdentificationService(CallService callService)
{
    private Task? _executeTask;
    private CancellationTokenSource? _stoppingCts;
    private Modem? _modem;

    public void StartExecuting(CancellationToken cancellationToken)
    {
        if (_modem is null) throw new InvalidOperationException("Can't start executing without modem");
        _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        _executeTask = Task.Run(async () =>
        {
            await DoWork(_stoppingCts.Token); // <-- here
            _modem.Close();
            _modem = null;
        }, cancellationToken);
    }


This service is being registered with Microsoft DI as a singleton.
When the
StartExecuting
StartExecuting
function is called, the
callService
callService
is correctly being passed.

However if I set a breakpoint inside the lambda of Task.Run,
callService
callService
is null there...

Any ideas?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Default parameter values in primary constructor
C#CC# / help
3y ago
✅ What is a primary constructor in C#
C#CC# / help
11mo ago
Primary Constructor
C#CC# / help
5mo ago
✅ what is a primary constructor? is it any similar to parameterless constructor?
C#CC# / help
16mo ago