I'm not sure I understand. I have sent many operations to a single
Session
instance. Cancellation Token is for Operations, not Objects. One cancellation token should refer to a “cancellable operation”. Once the
IsCancellationRequested
property in a cancellation token is set to true, it can’t be set to false again and you can't reuse the same cancellation token again after its cancelled. So if you were doing multiple things with a session that had a cancellation token attached to its
FileTransferProgress
event then all events would be cancelled, not just a single operation.
martin wrote:
Or do you have any other example of synchronous API with a cancellation token?
The Microsoft documentation states "Starting with .NET Framework 4, .NET uses a unified model for cooperative cancellation of asynchronous
or long-running synchronous operations." in this article:
https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads
Stephen Cleary shows the most simple example of using Cancellation Tokens in synchronous methods here:
https://blog.stephencleary.com/2022/03/cancellation-4-polling.html
Looking at C++ examples, the code looks very similar. The C# cancellation token could be linked to a stop token where
stoken.stop_requested()
can be checked to interrupt an operation the same way we check for
IsCancellationRequested
in C#. These patterns were modeled after C# so I'm sure there are people using them this way. Seen here:
https://www.nextptr.com/tutorial/ta1588653702/stdjthread-and-cooperative-cancellation-with-stop-token