I am working on porting the controller to asynchronous. Part of the work is associated with waiting for the operation of an asynchronous, canceled action on a one-time object using a cancellation token valid for the duration of the request. In this particular case, this WebClient.UploadStringTaskAsync(Uri uri, string data).
I know the correct way to undo asynchronous WebClient operations with cancellationToken.Register(() => webClient.CancelAsync()). However, it WebClientis created in the using statement, so it is located at the end of the block. As a result, a call webClient.CancelAsync()from a callback rightfully leads to a warning “Access to remote closure”. I found that CancellationToken.Register(Action callback)leads to an object CancellationTokenRegistrationthat implements IDisposableand cancels callbacks on deletion. At the end, my code looks like this:
using (var webClient = new WebClient())
using (cancellationToken.Register(() => webClient.CancelAsync())
{
await webClient.UploadStringTaskAsync(uri, data);
}
I made a console application to show that the code works the same way and cancels the token after placing a one-time object and registering a token, does not lead to a callback of a one-time object. I want to be sure: is this correct and safe?
: , . async , ?