© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
2 replies
MechWarrior99

❔ Cancel task on nested exception

I have a series of nested async methods, when a exception is thrown I want to cancel the task.
The main issue is that I need to do a
try cache
try cache
in a
for
for
loop in a nested method, so that we can get more detailed telemetry about it. That means that the methods just keep going. I could pass the CTS to the tasks instead, or access it through other means, but that also feels a little messy.

Hope this makes sense.

private CancellationTokenSource _tokenSource;
public async Task RunBigTask()
{
    _tokenSource = new CancellationTokenSource();
    // Some logic here...
    await OtherClass.RunSmallerTasks(_tokenSource.Token); 
    // Some other logic here...
}

// In another class...
public async Task RunSmallerTasks(CancellationToken ct)
{
    for(int i = 0; i < k; i++)
    {
      ct.ThrowIfCancellationRequested();
      try
      {
        await RunSmallTask();
      } 
      catch(Exception e)
      {
        // Sending telemetry here about the exception.
      }
    }
}
private CancellationTokenSource _tokenSource;
public async Task RunBigTask()
{
    _tokenSource = new CancellationTokenSource();
    // Some logic here...
    await OtherClass.RunSmallerTasks(_tokenSource.Token); 
    // Some other logic here...
}

// In another class...
public async Task RunSmallerTasks(CancellationToken ct)
{
    for(int i = 0; i < k; i++)
    {
      ct.ThrowIfCancellationRequested();
      try
      {
        await RunSmallTask();
      } 
      catch(Exception e)
      {
        // Sending telemetry here about the exception.
      }
    }
}
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

✅ CancellationtokenSource and Cancel Task
C#CC# / help
2y ago
Cancel long running task/method
C#CC# / help
2y ago
✅ async Task throws exception if not explicitly defined
C#CC# / help
3y ago