Thread/Task cancellation
    Gjiergji 
    gjiergji.koleka at gmail.com
       
    Fri Jul 28 18:17:18 UTC 2023
    
    
  
I am coming from a C# background. I understood that there is no 
async/await equivalent in D (except fibers which are not suitable 
for multi threading), but if I am using threads, what is the D 
idiom to implement cancellation?
Usually a long running thread looks like this (in C#):
```csharp
try
{
    while (!cancellationToken.IsCancellationRequested)
    {
       //do some work
       await SomethingAsync(cancellationToken);
       //do some other work
       await Task.Delay(TimeSpan.FromSeconds(5000), 
cancellationToken);
    }
}
catch (OperationCancelledException e) when (e.Token == 
cancellationToken)
{
    //someone cancelled any of the await calls above, we can 
swallow it or log it
}
```
The question is how do I pass a `cancellationToken` to the calls 
from the loop in order to terminate them before completion. For 
example, I learnt about `Thread.sleep` in phobos, but I cannot 
pass a cancellation token in order to cancel it before the 
intended sleep duration.
Thx.
    
    
More information about the Digitalmars-d-learn
mailing list