Thread/Task cancellation
Gjiergji
gjiergji.koleka at gmail.com
Wed Aug 2 05:47:18 UTC 2023
On Friday, 28 July 2023 at 20:13:24 UTC, Ruby The Roobster wrote:
> This is the only way I could think of doing this, since
> exceptions don't travel up the threads.
Thank you for pointing me in the right direction. I think that
exceptions are not really necessary in D for cancellation, as I
said, the code above was idiomatic C#.
Finally I come up with this code to achieve the same:
```d
void longRunningThread()
{
while (true)
{
if (receiveTimeout(3000.msecs, (bool cancel) {}))
{
writeln("Cancelled");
break;
}
else
{
//do some work
writeln("Another 3 seconds passed");
}
}
}
int main()
{
writeln("Press Enter to stop");
auto tid = spawn(&longRunningThread);
readln();
tid.send(true); //here we cancel
writeln("Press Enter to exit");
readln();
return 0;
}
```
Maybe someone add such examples to
https://wiki.dlang.org/Programming_in_D_for_CSharp_Programmers
which is anyway totally outdated.
More information about the Digitalmars-d-learn
mailing list